1

Is there a better way to do this

questionobjects = Questions.objects.all()
for questionobject in questionobjects:
        answerobjects = Answers.objects.filter(question=questionobject.id).count()

In the above query Answers model has foreign key relation with Questions. But in the above script the query Answer query executes based on the number of questionobjects.

Suppose there are 10 questionobjects then 10 separate answerobject queries take place. Is there a way to do this with a single query because as the number of questionobjects increases, it will be a problem because the number of answerobjects queries also increase

2 Answers 2

6

So it looks like you just care about the count of answers, rather than getting the actual answer objects. You can do this with annotations:

from django.db.models import Count
Question.objects.all().annotate(Count('answers'))
Sign up to request clarification or add additional context in comments.

4 Comments

how to write the above query to get questionobjects whose answers count is greater than 3
i know how do that using a sql query but iam new to django and have issues with it
@ChingChong Questions.objects.annotate(count=Count('answers')).filter(count__gt=3)
4

Take a look at annotation: Django Annotation

from django.db.models import Count
questions = Questions.objects.annotate(count=Count('answers'))

Then you can access the count with [q.count for q in questions]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.