Let's say I have the following model structure:
Parent():
Child():
parent = ForeignKey(Parent)
GrandChild():
child = ForeignKey(Child)
state = BooleanField()
num = FloatField()
I'm trying to from the Parent ViewSet
, recover the following:
- The number of children.
- The SUM of the 'num' fields when 'state' is True.
I can do the following:
queryset = Parent.objects\
.annotate(child_count=Count('child'))\
.annotate(sum_total=Sum('child__grandchild__num'))
This gives me (1) but instead of (2) it gives me the SUM for ALL grandchildren. How can I filter the grandchildren appropriately while ensuring I have all of the Parent
objects still in the QuerySet?
Try using filter before the annotate