django - query filter on manytomany is empty

2019-03-14 05:32发布

In Django is there a way to filter on a manytomany field being empty or null.

class TestModel(models.Model):
    name = models.CharField(_('set name'), max_length=200)
    manytomany = models.ManyToManyField('AnotherModel', blank=True, null=True)

print TestModel.objects.filter(manytomany__is_null=True)

2条回答
贼婆χ
2楼-- · 2019-03-14 05:48

Adding to @Bernhard answer, other possible solution can be achieved using the Q() object.

from django.db.models import Q

filters = Q(manytomany=None)

TestModel.objects.filter(filters)

Negation:

filters = ~Q(manytomany=None)

TestModel.objects.filter(filters)
查看更多
【Aperson】
3楼-- · 2019-03-14 06:09
print TestModel.objects.filter(manytomany=None)
查看更多
登录 后发表回答