多对多加Q的Django滤波器

2024-04-24 22:58:48 发布

您现在位置:Python中文网/ 问答频道 /正文

class ModelA:
    m2m1 = Foreignkey relatedname = 'm2ms'

我们可以使用以下方法获得m2m1对象:

modela_instance.m2ms.all()

样本输出:

for x in ModelA.objects.all():
    print x.m2ms.all().values_list('id', Flat=True)

1,2,3
1,
[]
2
4,5

因此,如果我想获取m2ms具有ID 1、2、3的所有实例(也可以有更多)。然后我可以这样做:

ModelA.objects.filter(m2ms__id=1).filter(m2ms__id=2).filter(m2ms__id=3)

我怎么能用Q来做这个?你知道吗

ModelA.objects.filter(Q(some_boolean=True, simple_field=5) | Q(some_boolean=False, here m2ms should be 1,2,3 lets say))  

根据以上要求,我的意思是:

当(某些布尔值=True,简单字段=5)或某些布尔值=False时,它应该返回记录,m2ms应该有1,2,3(可以有更多)。你知道吗

输出:

If some_boolean=True, then we dont bother about m2ms. These records should have simple_field with value 5
If some_boolean=False, then for all records, each_record.m2ms.all().values_list('id', Flat=True) should contains 1,2,3. For example: 1)[1,2,3], 2)[1,2,3,4], 3)[1,2,3,5,6,7]

请让我知道更多的澄清。你知道吗


Tags: idfalsetrueforobjectssomeallfilter