【问题标题】:Django using foreignKey to retrieve one attribute in a queryDjango 使用 foreignKey 检索查询中的一个属性
【发布时间】:2014-11-25 04:22:16
【问题描述】:

在我的 django 代码中,我有这两个对象:

class A(models.Model):
  ...

class B(models.Model)
  flag = models.BooleanField(default=False)
  type = models.ForeignKey(A)
  ...

我想做类似的事情:

A.objects.filter(...)

在我的过滤器中,我只想链接至少有 1 个 B 且标志 = True 的 A。 是否可以直接使用过滤器执行此操作?而不是有一个循环,然后:

a.b_set.filter(flag__exact=1).count() > 0

【问题讨论】:

    标签: django filter models


    【解决方案1】:

    指定 b__flag=... 会给你想要的。

    A.objects.filter(b__flat=True)
    

    以上可能会产生重复的A 对象。防止这种情况,使用QuerySet.distinct

    A.objects.filter(b__flat=True).distinct()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多