【问题标题】:Q objects and the '&' operator in djangodjango 中的 Q 对象和 '&' 运算符
【发布时间】:2011-05-30 05:46:51
【问题描述】:

我有一个奇怪的问题。

我有 3 个对象。都一样

class Articles(models.Model):
    owner = models.ForeignKey(Author)
    tags = models.ManyToManyField('Tag')


class Tag(models.Model):
     name = models.CharField(max_length=255)

所以我有 3 篇文章。使用所有相同的标签:'tag1' 和 'tag2'

我有疑问

actionsAll = Articles.objects.filter((Q(tags__name__exact="tag1") | Q(tags__name__exact="tag2"))).distinct()

这给了我所有的文章。它将返回 6 篇没有 distinct() 的文章,因为它会收集每篇文章 2x,因为它们都有两个标签。

但是对于这个查询:

actionsAll = Articles.objects.filter((Q(tags__name__exact="tag1") & Q(tags__name__exact="tag2"))).distinct()

这没有给我任何文章。 由于文章包含两个标签,它应该都返回它们不应该吗?

【问题讨论】:

  • 替换 | and & 加上关键字“or”和“and”就可以了。
  • or 和 and 与| 和& 做了非常 不同的事情;不要试图将它们用作替代品。
  • 它的工作方式对我来说应该是正确的。你能解释一下这里发生了什么以及为什么我不应该使用它吗?为了得到我想要的行为,我唯一需要做的就是使用“and”作为并集,使用“or”作为反向逻辑的交集。我知道您应该在替换另一个之前考虑一下,但在我的情况下,我的查询按我的意愿工作。
  • and 和 or 不提供“加入”到 & 和 | 所做的查询;相反,他们根据“真实性”返回其中一个操作数。它可能适用于您拥有的数据,但随着您的数据扩大,您会发现其中存在逻辑错误。

标签: django django-q


【解决方案1】:

如果您查看它生成的 SQL,您会发现它会检查 same 标记是否具有两个名称。您需要的是一个遍历关系的IN query 或EXISTS 查询。

【讨论】:

    【解决方案2】:
    ** import Q from django
    from *models import SuperUser, NameUser
    import operator
    
    # we do not know the name in the superhero
    super_users = SuperUser.objects.all()
    q_expressions = [Q(username=user.username) for user in super_users]
    # we have bind super_hero with user
    name_superheroes_qs = models.NameUser.objects.filter(reduce(operator.or_, q_expressions))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-13
      • 2015-06-23
      • 2016-05-28
      • 2013-05-30
      • 2014-02-06
      • 2015-07-15
      • 2014-02-26
      • 2016-01-05
      相关资源
      最近更新 更多