Django: Can we use .exclude () on .get () in django querysets

advertisements

Can we use

 MyClass.objects.get(description='hi').exclude(status='unknown')


Your code works as expected if you do the exclude() before the get():

MyClass.objects.exclude(status='unknown').get(description='hi')

As @Burhan Khalid points out, the call to .get will only succeed if the resulting query returns exactly one row.

You could also use the Q object to get specify the filter directly in the .get:

MyClass.objects.get(Q(description='hi') & ~Q(status='unknown'))

Note that the Q object is only necessary because you use a .exclude (and Django's ORM does not have a not equal field lookup so you have to use .exclude).

If your original code had been (note that .exclude has been replaced with .filter):

MyClass.objects.filter(status='unknown').get(description='hi')

... you could simply do:

MyClass.objects.get(status='unknown', description='hi')