1
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))  

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

它应该在 (some_boolean=True, simple_field=5) OR some_boolean=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]

请让我知道更多说明。

4

0 回答 0