简体   繁体   English

Django 使用 Q 过滤查询

[英]Django filtering queries with Q

I have confusing problem in querying in django.我在 Django 中查询时遇到了令人困惑的问题。 I know its not a bug and it is something that I don't know.我知道这不是一个错误,这是我不知道的事情。

So models are:所以模型是:

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

class AttributeValue(models.Model):
    value = models.CharField(max_length=255)
    product = models.ForeignKey(Product, related_name='attribute_values', on_delete=models.CASCADE)

I have one product object called T-shirt and it has two AttributeValue with ids 1, 2. And when I filter like this (1):我有一个名为T 恤的产品对象,它有两个 ID 为 1、2 的AttributeValue 。当我像这样过滤时 (1):

Product.objects.filter(Q(attribute_values__pk__in=[1, 2]))

Its returning my T-shirt object.它返回了我的T 恤对象。 But when I filter like this (2)但是当我像这样过滤时 (2)

Product.objects.filter(Q(attribute_values__pk__in=[1]) & Q(attribute_values__pk__in=[2]))

there is no queryset found here.这里没有找到查询集。 How is this happening?这是怎么回事? Previous codes are just examples and I have project that really need to do with this second filter (2).以前的代码只是示例,我的项目确实需要使用第二个过滤器 (2)。

This will never return any query results:永远不会返回任何查询结果:

Product.objects.filter(Q(attribute_values__pk__in=[1]) & Q(attribute_values__pk__in=[2]))

# Equivalent to:
Product.objects.filter(attribute_values__pk=1).filter(attribute_values__pk=2)

Why?为什么? Because there is no object that simultaneously possesses both a primary key of 1 AND a primary key of 2 .因为不存在同时拥有主键1和主键2

You want the Q objects to be "OR"ed together instead of "AND"ed, so this is what you actually want:您希望将Q对象“或”在一起而不是“与”,所以这就是您真正想要的:

Product.objects.filter(Q(attribute_values__pk__in=[1]) | Q(attribute_values__pk__in=[2]))

But why use Q objects when you can achieve the same without them?但是,如果没有Q对象也能达到同样的效果,为什么还要使用Q对象呢? For instance:例如:

Product.objects.filter(attribute_values__pk__in=[1, 2])

In this在这

Product.objects.filter(Q(attribute_values__pk__in=[1]), Q(attribute_values__pk__in=[2]))

your are using Q expression with and which will not setisfy what you want so for expected output either:您正在使用 Q 表达式,并且它不会设置您想要的预期输出:

Product.objects.filter(Q(attribute_values__pk__in=[1, 2]))

or或者

Product.objects.filter(Q(attribute_values__pk__in=[1]) | Q(attribute_values__pk__in=[2]))

but you should use the first one without Q expression但你应该使用第一个没有 Q 表达式的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM