在 manytomany 上 django-query 过滤器为空

在 Django 中,有一种方法可以对空或空的许多字段进行过滤。

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)
39854 次浏览
print TestModel.objects.filter(manytomany=None)

添加到@Bernhard 回答,其他可能的解决方案可以通过使用 Q()对象来实现。

from django.db.models import Q


filters = Q(manytomany=None)


TestModel.objects.filter(filters)

否定:

filters = ~Q(manytomany=None)


TestModel.objects.filter(filters)

尽管这个主题已经有了答案,但这可能会有所帮助。尝试查找:

empty = TestModel.objects.filter(manytomany__isnull = True)
#........If you want to get their counter part
not_empty = TestModel.objects.filter(manytomany__isnull = False)

Basically, you get two query sets: one where your manytomany fields are empty, and the other with objects that have data in the manytomanyfield.

希望这对你有所帮助!

这是一个老问题,但我需要它,所提供的答案不适合我,但我修复了它,并得到了适当的过滤(在 Django 2.2)这是如何:

testModel.objects.filter(testmodel__anothermodel=None)

正如你可以看到使用模型名称所有小写然后两个下划线然后许多到许多模型名称,这样做为我