[Fixed]-Django : Can we use .exclude() on .get() in django querysets

30👍

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')

1👍

You want instead:

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

.get() will raise MultipleObjectsReturned if your query results in more than one matching set; which is likely to happen considering you are searching on something that isn’t a primary key.

Using filter will give you a QuerySet, which you can later chain with other methods or simply step through to get the results.

Leave a comment