Django, annotate with prefetching

I have a Django API of a farm.

class Group(models.Model):     name = models.CharField()     milking = models.BooleanField()     sub_groups = models.ForeignKey('self',                                    on_delete=models.DO_NOTHING)     herd = models.ForeignKey(on_delete=models.CASCADE,                              to=Herd)      def __str__(self):         return   class Cow(models.Model):     management_id = models.CharField()     eid_number = models.CharField(primary_key=True,                                   blank=False)     group = models.ForeignKey(Group,                               on_delete=models.PROTECT)     days_in_pasture = models.IntegerField()     hours_in_pasture = models.IntegerField()      def __str__(self):         return self.eid_number 

I want the queryset in the view to return all the Groups and every group’s cows data and annotate the number of days in the pasture for each group (annotate the sum of all the group’s cows days in the pasture).

So far I’ve got something like this:

class GroupView(ModelViewSet):     filter_backends = GROUP_FILTERS      def get_queryset(self):         query_set = Group.objects.all().prefetch_related('cow').annotate(amount_of_cows=Count('cow__days_in_pasture'))         return query_set 
Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.