A
A
Anton Manevant2015-11-09 13:49:47
Django
Anton Manevant, 2015-11-09 13:49:47

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 CarReviewswith ForeignKeyto a table Car.
You need to get everything Carwith a count CarReviewsgreater 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()

Fell into a stupor. Suggest a solution.)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-11-09
@Manevant

from django.db.models import Count
Car.objects.annotate(reviews_count=Count('car_rewiews')).filter(reviews_count__gt=N)

By the way, you have a bug (not me) in car_reviews. car_reviews.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question