How can I use Django Querysets and Q() to compare against objects of the same model type?

267 views Asked by At

I have a Django model named MyModel. m is an instance of MyModel. I would like to use Django QuerySets to find all the instances of MyModel that are not m. How to do it? This doesn't work:

MyModel.objects.filter(~Q(m))

It seems you can query against attributes of MyModel using Q(). However I don's see how I can use Q to include/exclude instances of MyModel itself. Is this doable? If so, how? If not, what is the most efficient and elegant way to get at what I'm trying to do?

1

There are 1 answers

1
Ghopper21 On BEST ANSWER

Use the model's pk (primary key) field:

MyModel.objects.exclude(pk=m.pk)

To exclude another model n also (additional question asked in comment below), you could do:

MyModel.objects.exclude(pk=m.pk).exclude(pk=n.pk)

More generally, to exclude a list of instances list_of_instances, use the __in syntax:

MyModel.objects.exclude(pk__in=[instance.pk for instance in list_of_instances])