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?
Use the model's
pk
(primary key) field:To exclude another model
n
also (additional question asked in comment below), you could do:More generally, to exclude a list of instances
list_of_instances
, use the__in
syntax: