问题描述
我有一个 CartItem
模型,该模型具有一个 AttributeChoice
模型的ManyToMany字段。因此,例如 CartItem
可以具有 AttributeChoice
小和红色。
I have a CartItem
model with a ManyToMany field to a AttributeChoice
model. So for example a CartItem
can have AttributeChoice
"Small" and "Red".
我想找到我的 CartItem
,它们都具有 Small和 Red属性。如果我执行以下操作:
I want to then find my CartItem
that both have attributes "Small" and "Red". If I do the following:
CartItem.objects.get(cart=cart, product=product, attribute__in=attribute_list)
其中 attribute_list
是<$ c $的列表c>小型和红色的AttributeChoice 对象。然后,我还将获得仅具有小或红色但不具有两者的对象。
Where attribute_list
is a list of AttributeChoice
objects for "Small" and "Red". Then I will also get objects that only have "Small" or "Red", but not both.
因此,此查询将都匹配:
So this query would both match:
- CartItem C,小红色
- CartItem B,小
- CartItem C,红色
我想要的是仅与CartItem A匹配的查询。
While what I want is a query that would only match CartItem A.
现在...我可以创建许多AND语句,但是我需要一个灵活的解决方案,可以包含1或100个要过滤的属性。因此,传递给它一个对象列表将是很棒的。
Now... I could create a lot of AND-statements, but I need a solution that is flexible and can contain 1 or 100 of attributes to filter for. So to pass it a list of objects would be great.
想法?
推荐答案
此问题的解决方案发布在。
The solution to this problem was posted in this thread.
这是我编写查询的方式:
This is how I wrote my query:
CartItem.objects.filter(cart=cart, product=product, attribute__in=attribute_list).annotate(num_attr=Count('attribute')).filter(num_attr=len(attribute_list))
这篇关于Django过滤器,其中ManyToMany字段包含列表的全部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!