鉴于这些 Django 模型:
from django.db import models
class Thing(models.model):
name = models.CharField('Name of the Thing')
class Category(models.model):
name = models.CharField('Name of the Category')
things = models.ManyToManyField(Thing, verbose_name='Things', related_name='categories')
我真的很难构建一个查询集来返回所有类别中的所有事物。
为了澄清,假设我们有 5 个类别,ID 为 1、2、3、4、5。
我想找到类别 2 和 3 中的所有事物。
我可以很容易地找到类别 2 或 3 中的所有事物。例如这个:
Thing.objects.filter(categories__in=[2,3])
似乎只返回类别 2 或 3 中的事物。
还有类似的东西:
Thing.objects.filter(Q(categories=2)|Q(categories=3))
也是,但是这个:
Thing.objects.filter(Q(categories=2)&Q(categories=3))
什么都不返回。
我可能会设想这样的事情:
Thing.objects.filter(categories__contains=[2,3])
但这当然是一个梦想,因为
contains
对字符串而不是 m2m 集进行操作。
这里有我缺少的标准技巧吗?