django - query filter on manytomany is empty

DjangoDjango Queryset

Django Problem Overview


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)

Django Solutions


Solution 1 - Django

print TestModel.objects.filter(manytomany=None)

Solution 2 - Django

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)

Solution 3 - Django

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - DjangoBernhard VallantView Answer on Stackoverflow
Solution 2 - DjangoRakmoView Answer on Stackoverflow
Solution 3 - DjangoFiringamView Answer on Stackoverflow