Find all the objects that does not have any reverse lookup m2m values

63 views Asked by At

I have a list of contacts and each Contact can belong to many ContactList. What I need to do is find all contacts that does not belong to any ContactList (ie. orphan contacts).

class ContactList(models.Model):
    name = models.CharField()
    contacts = models.ManyToManyField(Contact)

class Contact(models.Model):
    name = models.CharField()

I tried the following but it doesn't work, because contactlist_set is a reverse lookup field and not a model field.

Contact.objects.filter(contactlist_set=None)

Can some give me some direction to proceed?

Thanks

1

There are 1 answers

1
nik_m On BEST ANSWER

I think this should work for you:

Contact.objects.filter(contactlist__isnull=False)