Frage

I want to do something like

query.annotate(Count('foreign_model_relation', somefield_from_foreign_model=some_value))

That means, i want to count, how many objects from another queryset are pointing to this object. The difference between using something like filter(in=other_queryset) is, that i would like to combine this in one query, to avoid generating one query per object.

Simplified Models:

  • Group
  • Object
    • group (Group)
  • Vote
    • object (Object)
    • up (Boolean)

Now i want to query the up/down count of all Objects for one Group, with one or two queries, not with one/two queries per Object.

War es hilfreich?

Lösung

You can do this with two queries:

YourObject.objects.filter(vote__up=True, group=some_group).annotate(total_votes_up=Count('vote'))
YourObject.objects.filter(vote__up=False, group=some_group).annotate(total_votes_down=Count('vote'))

But I think that should exist some more elegante way to do this.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top