Ideally I would like to use the Count aggregator to count distinct appearances of two fields, instead of just one:
q = Tag.objects.annotate(success=Count(['artifact__event__session', 'artifact'], distinct=True))
but this does not seem to be allowed.
I came up with the hacky solution of concatenating the fields I want to count the distinct combinations of:
q = Tag.objects.annotate(success=Count(Concat('artifact__event__session', 'artifact'), distinct=True))
But this does not seem like the right thing to do.
Is there a better way?
More background information:
The actual query is more like:
q = Tag.objects.annotate(success=Count(Concat('artifact__event__session', 'artifact'), filter=Q(artifact__event__success=True, artifact__event__user=user), distinct=True))
which has the meaning:
"For each tag, give me the number of distinct session-artifact combinations of artifacts that are tagged with that tag and sessions that included that artifact, where an event that belongs to this user was successful"
with the models being:
class Artifact(models.Model):
tags = models.ManyToManyField(Tag)
...
class Event(models.Model):
artifact = ForeignKey(Artifact)
session = ForeignKey(Session)
success = BooleanField()
user = ForeignKey(User)
...
class Session(models.Model):
...
question from:
https://stackoverflow.com/questions/65904151/django-how-to-annotate-query-with-count-of-distinct-occurrences-of-field-combin 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…