Django Database query for counting related objects

I have a question model:

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

and its associated response model:

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

I want to filter out all the unanswered questions. How can I do this in a view?

+6
source share
1 answer

Below is a request to receive all questions that are not related to answers:

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

Update:
You can behave using any parameters annotate, the same as real model fields in the filtering method, for example, all questions that have more than three answers:

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

:
?
ORM -db SQL, SQL , , SELECT, , . :

SELECT count(*) from my_table;

count , , , .
Django ORM SQL, funtion SQL .

anneate aboute

+4

All Articles