Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django过滤器,其中许多字段包含列表中的所有内容_Python_Django - Fatal编程技术网

Python Django过滤器,其中许多字段包含列表中的所有内容

Python Django过滤器,其中许多字段包含列表中的所有内容,python,django,Python,Django,我有一个CartItem模型,其中有一个AttributeCoice模型的多个字段。因此,例如,CartItem可以具有AttributeCooice“小”和“红” 然后我想找到我的CartItem,它们都有属性“Small”和“Red”。如果我这样做: CartItem.objects.get(cart=cart, product=product, attribute__in=attribute_list) 其中,attribute\u list是“小”和“红”的attributechice

我有一个
CartItem
模型,其中有一个
AttributeCoice
模型的多个字段。因此,例如,
CartItem
可以具有
AttributeCooice
“小”和“红”

然后我想找到我的
CartItem
,它们都有属性“Small”和“Red”。如果我这样做:

CartItem.objects.get(cart=cart, product=product, attribute__in=attribute_list)
其中,
attribute\u list
是“小”和“红”的
attributechice
对象列表。然后我还将得到只有“小”或“红色”的对象,但不是两者都有

因此,此查询将同时匹配:

  • CartItem A,小,红色
  • B项,小型
  • C项,红色
而我想要的是一个只匹配CartItem a的查询

现在。。。我可以创建很多AND语句,但我需要一个灵活的解决方案,可以包含1或100个要筛选的属性。因此,向其传递一个对象列表将非常好


想法

此问题的解决方案已发布在中

以下是我编写查询的方式:

CartItem.objects.filter(cart=cart, product=product, attribute__in=attribute_list).annotate(num_attr=Count('attribute')).filter(num_attr=len(attribute_list))

请出示您的型号类别,证明FCOVINGTON是正确的。有一个重复的问题,以不同的方式形成了正确的答案。我也会把答案贴在这里。