django filter on many to many along with Q

拜拜、爱过 提交于 2019-12-11 09:41:24

问题


class ModelA:
    m2m1 = Foreignkey relatedname = 'm2ms'

We can get m2m1 objects using:

modela_instance.m2ms.all()

Sample output:

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

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

So, if I want fetch all instances whose m2ms has ids 1,2,3 (can have more too). Then I can do this:

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

How can I do this with Q ?

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

From above requirement, I mean:

It should return records when (some_boolean=True, simple_field=5) OR some_boolean=False, m2ms should have 1,2,3(can have more).

Output:

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]

Please let me know for more clarification.

来源:https://stackoverflow.com/questions/24191563/django-filter-on-many-to-many-along-with-q

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!