Django; Querying the Database By Counts Of Related Objects

Viewed 79

I have a question model:

class Question(models.Model):
....

and an answer model related to it:

class Answer(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)

I want to filter out all the questions with no answers. How can I do that in the view?

1 Answers

below query get all questions that not related answers:

Question.objects.annotate(answer_count=Count('answer')).filter(answer_count=0)

Update:
You can behave by every annotate parameters same as real model fields in filter method, for example all questions that have more than three answer:

Question.objects.annotate(answer_count=Count('answer')).filter(answer_count__gt=3)

NOTE:
How annotate method works?
In back of all relational-db ORMs transactions handle by SQL language, and SQL prefer some extra functions that made more flexibility in many actions, specificly in SELECT statement, for sample some times we needs average or count of columns in multiples rows, see below:

SELECT count(*) from my_table;

if upper count function not prefered, we must fetch all records first, and in another step calculate length of results, this method is difficult and have many pros.
Django ORM prefered equal SQL usable functions that only must using in annotate funtion and translate to SQL before run.

More info aboute annotate method

Related