Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

Django: How to annotate query with Count of distinct occurrences of field combination?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...