Reputation: 834
I have two models:
class Property(models.Model):
# code here...
class AccommodationType(models.Model):
property = models.ForeignKey(Property, related_name='accommodation_types')
# rest of code here...
What I'm trying to to is to annotate Property's queryset with count of related AccommodationType's and filter it by the value of this count. So here is my code:
qs = Property.objects.all()
qs.annotate(acc_types_count=Count('accommodation_types'))
filtered = qs.filter(acc_types_count=1)
and here I got the error:
django.core.exceptions.FieldError: Cannot resolve keyword 'acc_types_count' into field. Choices are: # ...rest of the fields
Where I am wrong?
Upvotes: 0
Views: 454
Reputation: 599778
annotate
, like filter
, doesn't mutate the queryset but returns a new one. You need to reassign that to qs
:
qs.annotate(acc_types_count=Count('accommodation_types'))
Or combine it with the original query:
qs = Property.objects.all().annotate(acc_types_count=Count('accommodation_types'))
Upvotes: 1