在 Django 中查询 ManyToManyField 的确切内容
如何通过检查对象的 ManyToManyField 关系的成员是否完全匹配给定的对象列表来查询对象?
例如,假设
class Topping(models.Model):
# ...
class Pizza(models.Model):
# ...
toppings = models.ManyToManyField(Topping)
我想获得所有包含意大利辣香肠和洋葱的比萨饼:
pep = Topping(name='pepperoni')
pep.save()
onion = Topping(name='onion')
onion.save()
tops = [pep, onion]
p = Pizza.objects.filter(toppings__eq=tops)
Django 提供了 __in 运算符,但不提供 __eq
。我该如何做同等的事情?
谢谢。
How do I query for an object by checking whether the members of its manyToManyField relation exactly matches a given list of objects?
For example, given
class Topping(models.Model):
# ...
class Pizza(models.Model):
# ...
toppings = models.ManyToManyField(Topping)
I want to get all pizzas that have exactly pepperoni and onions:
pep = Topping(name='pepperoni')
pep.save()
onion = Topping(name='onion')
onion.save()
tops = [pep, onion]
p = Pizza.objects.filter(toppings__eq=tops)
Django provides the __in
operator, but not __eq
. How do I do the equivalent?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您如何过滤所有配料,然后确保您选择的披萨与您指定的配料数量完全相同。
How about you filter for all toppings, then ensure that you select the pizza with exactly the number of toppings you specified.
只需链接您的过滤器即可获得您想要的内容:
我还没有找到更好的方法来做到这一点。
Just chain your filters to get what you want:
I haven't come across a better way to do this.