在 Django 中查询 ManyToManyField 的确切内容

发布于 2025-01-02 23:21:20 字数 513 浏览 1 评论 0原文

如何通过检查对象的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

度的依靠╰つ 2025-01-09 23:21:20

您如何过滤所有配料,然后确保您选择的披萨与您指定的配料数量完全相同。

from django.db.models import Q
import operator
pizza = (Pizza.objects
    .filter(reduce(operator.or_, [Q(toppings=topping) for topping in tops]))
    .annotate(count=Count('toppings'))
    .filter(count=len(tops))
    )

How about you filter for all toppings, then ensure that you select the pizza with exactly the number of toppings you specified.

from django.db.models import Q
import operator
pizza = (Pizza.objects
    .filter(reduce(operator.or_, [Q(toppings=topping) for topping in tops]))
    .annotate(count=Count('toppings'))
    .filter(count=len(tops))
    )
_失温 2025-01-09 23:21:20

只需链接您的过滤器即可获得您想要的内容:

pep = Topping(name='pepperoni')
pep.save()
onion = Topping(name='onion')
onion.save()
tops = [pep, onion]
p = Pizza.objects.filter(toppings__id=pep.id).filter(toppings__id=onion.id)

我还没有找到更好的方法来做到这一点。

Just chain your filters to get what you want:

pep = Topping(name='pepperoni')
pep.save()
onion = Topping(name='onion')
onion.save()
tops = [pep, onion]
p = Pizza.objects.filter(toppings__id=pep.id).filter(toppings__id=onion.id)

I haven't come across a better way to do this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文