Django excluding specific instances from queryset without using field lookup

DjangoFilteringDjango Queryset

Django Problem Overview


I sometimes have the need to make sure some instances are excluded from a queryset.
This is the way I do it usually:

unwanted_instance = MyModel.objects.get(pk=bad_luck_number)
uninteresting_stuff_happens()
my_results = MyModel.objects.exclude(id=unwanted_instance.id)

or, if I have more of them:

my_results = MyModel.objects.exclude(id_in=[uw_in1.id, uw_in2.id, uw_in3.id])

This 'feels' a bit clunky, so I tried:

my_ideally_obtained_results = MyModel.objects.exclude(unwanted_instance)

Which doesn't work. But I read here on SO that a subquery can be used as parameter for exclude.
Am I out of luck? Am I missing some functionality (checked the docs, but didn't find any useful pointer)

Django Solutions


Solution 1 - Django

The way you're already doing it is the best way.

If it's a model-agnostic way of doing this you're looking for, don't forget that you can do query.exclude(pk=instance.pk).

Just as an aside, if Django's ORM had an identity mapper (which it doesn't at present), then you would be able to do something like MyModel.objects.filter(<query>).all().remove(<instance>), but you're out of luck in that regard. The way you're doing it (or the one above) is the best you've got.

Oh, and also you can do much better than that in query with a list comprehension: query.exclude(id__in=[o.id for o in <unwanted objects>])

Solution 2 - Django

The Given answer is perfect and try this which works fine for me

step 1)

 from django.db.models import Q

step 2)

 MyModel.objects.filter(~Q(id__in=[o.id for o in <unwanted objects>]))

Solution 3 - Django

You can put your unwanted items in a list , and a fetch all items except those in the list like so:

MyModel.objects.exclude(id__in=[id1,id2,id3 ])

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
QuestionAgosView Question on Stackoverflow
Solution 1 - DjangoobeattieView Answer on Stackoverflow
Solution 2 - DjangokartheekView Answer on Stackoverflow
Solution 3 - DjangoSeyyid SaidView Answer on Stackoverflow