【问题标题】:better way to query in django在 django 中查询的更好方法
【发布时间】:2012-06-07 11:01:59
【问题描述】:

有没有更好的方法来做到这一点

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

在上面的查询中Answers 模型与Questions 有外键关系。但在上面的脚本中,查询答案查询是根据问题对象的数量执行的。

假设有 10 个问题对象,然后发生 10 个单独的答案对象查询。有没有办法用单个查询来做到这一点,因为随着 questionobjects 数量的增加,这将是一个问题,因为 answerobjects 查询的数量也会增加

【问题讨论】:

    标签: django django-models django-views django-queryset


    【解决方案1】:

    所以看起来您只关心答案的数量,而不是获取实际的答案对象。您可以使用注释来做到这一点:

    from django.db.models import Count
    Question.objects.all().annotate(Count('answers'))
    

    【讨论】:

    • 上面的查询如何写得到答案数大于3的questionobjects
    • 我知道如何使用 sql 查询来做到这一点,但我是 django 新手并且遇到了问题
    • @ChingChong Questions.objects.annotate(count=Count('answers')).filter(count__gt=3)
    【解决方案2】:

    看一下注解:Django Annotation

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

    然后您可以使用[q.count for q in questions] 访问计数

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2011-06-07
      • 2017-08-24
      • 2012-05-16
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多