【问题标题】:Filter related model django过滤器相关模型django
【发布时间】:2017-06-22 17:17:14
【问题描述】:

我正在构建示例 django polls 应用程序。我想排除所有没有选择的民意调查。为此,我必须访问相关的选择对象:

return Question.objects.filter(
pub_date__lte=timezone.now()
).exclude(
    choice_set__count=0
).order_by('-pub_date')[:5]

但是这个查询会导致字段错误:

无法将关键字“choice_set”解析为字段。选项有:choice、id、pub_date、question_text

如何从查询中查询相关模型?

【问题讨论】:

    标签: python django django-queryset


    【解决方案1】:

    _set 仅在您使用它来检索查询集之外的相关模型时适用,相反,如错误所示,您可以只使用 choice

    .exclude(choice__isnull=True)
    

    【讨论】:

      【解决方案2】:

      要过滤相关模型,您只需使用小写的模型名称 - 您可以看到 choice 是可用字段之一。

      但是,这仍然行不通;没有要过滤的 __count 属性。您可以使用注解添加一个,但有一种更简单的方法:与None 进行比较:

      .exclude(choice=None)
      

      【讨论】:

        【解决方案3】:

        Choice 模型中,将related_name 设置为Question 外键。 示例:

        class Choice(models.Model):
            question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices')
            # other code..
        

        然后你的查询应该是这样的:

        return (Question.objects
                .filter(pub_date__lte=timezone.now(),
                        choices__isnull=False)
                .order_by('-pub_date')[:5])
        

        注意:没有 `__count' 查找。如果您想依赖计数,请查看docs on this

        文档:https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.related_name

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-01-19
          • 2020-12-21
          • 2018-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-04
          相关资源
          最近更新 更多