在django中查询的更好方法

Chi*_*ong 1 django django-models django-queryset django-views

有一个更好的方法吗

questionobjects = Questions.objects.all()
for questionobject in questionobjects:
        answerobjects = Answers.objects.filter(question=questionobject.id).count()
Run Code Online (Sandbox Code Playgroud)

在上面的查询Answers模型中有外键关系Questions.但是在上面的脚本中,查询Answer查询基于questionobjects的数量执行.

假设有10个问题对象,则会发生10个单独的回答对象查询.有没有办法使用单个查询执行此操作,因为随着questionobjects数量的增加,这将是一个问题,因为answerobjects查询的数量也增加

Dan*_*man 6

所以看起来你只关心答案的数量,而不是得到实际的答案对象.您可以使用注释执行此操作:

from django.db.models import Count
Question.objects.all().annotate(Count('answers'))
Run Code Online (Sandbox Code Playgroud)