John
John

Reputation: 21927

django - query filter on manytomany is empty

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)

Upvotes: 128

Views: 46759

Answers (4)

Baraa Al-jabali
Baraa Al-jabali

Reputation: 147

this is an old question but I needed it and the provided answers didn't work for me, but I did fix it and got the proper filtering (on Django 2.2) this is how:

testModel.objects.filter(testmodel__anothermodel=None)

as you can see using the model name all lower case then two underscores then the many to many model name that did it for me

Upvotes: 0

Spartan 117
Spartan 117

Reputation: 129

Even though the topic has already an answer this could be of help. Try with lookups:

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.

Hope this could be of some help!

Upvotes: 3

Rakmo
Rakmo

Reputation: 1982

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)

Upvotes: 14

Bernhard Vallant
Bernhard Vallant

Reputation: 50796

print TestModel.objects.filter(manytomany=None)

Upvotes: 205

Related Questions