Django过滤器,其中ManyToMany字段包含所有列表

时间:2015-10-06 06:33:14

标签: python django

我有一个CartItem模型,其中包含一个AttributeChoice模型的ManyToMany字段。例如,CartItem可以AttributeChoice“小”和“红色”。

我想找到我的CartItem,它们都具有“小”和“红”的属性。如果我执行以下操作:

CartItem.objects.get(cart=cart, product=product, attribute__in=attribute_list)

attribute_list是“小”和“红”的AttributeChoice个对象列表。然后我也会得到只有“小”或“红色”的物体,但不能同时获得两者。

所以这个查询都匹配:

  • CartItem A,小,红色
  • CartItem B,小
  • CartItem C,红色

虽然我想要的是一个只能与CartItem A匹配的查询。

现在......我可以创建很多AND语句,但我需要一个灵活的解决方案,可以包含1或100个要过滤的属性。所以要传递一个对象列表会很棒。

想法?

1 个答案:

答案 0 :(得分:8)

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))
相关问题