Reputation: 8326
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')
Upvotes: 0
Views: 1695
Reputation: 37319
Use a values
clause to group prior to annotating.
qs = B.objects.values('a').annotate(max_value=Max('value'))
Upvotes: 1