0

I would like to annotate a queryset based on a foreign key, i.e.

class A(models.Model):
    name = models.CharField(max_length=200)

class B(models.Model):
    value = models.IntegerField()
    a = models.ForeignKey(A)

I would like to annotate the B queryset with Max, but each Max being filtered to the a foreign key.

I have a feeling I would have to filter out the foreign key I wanted, and then annotate.

qs = B.objects.filter(a=some_specific_instance_of_A).annotate(max_value=Max('value'))

But would like to do something like

qs = B.objects.annotate(max_value=Max('value'), key='a')
C.B.
  • 8,096
  • 5
  • 20
  • 34

1 Answers1

1

Use a values clause to group prior to annotating.

qs = B.objects.values('a').annotate(max_value=Max('value'))
Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83