Answer the question
In order to leave comments, you need to log in
How to create a Queryset with a filter by the number of related objects in another table?
Previously, I did not experience any particular difficulties in building querysets, but here it's a real problem :)
There is a Table CarReviews
with ForeignKey
to a table Car
.
You need to get everything Car
with a count CarReviews
greater than N. N is a variable.
class CarRewiews(models.Model):
car = models.ForeignKey(Car, verbose_name=_('Car'), related_name='car_rewiews')
class Car(models.Model):
somefield = models.TextField()
Answer the question
In order to leave comments, you need to log in
from django.db.models import Count
Car.objects.annotate(reviews_count=Count('car_rewiews')).filter(reviews_count__gt=N)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question