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.
- Passing a user, request to forms
- How to check whether virtualenv was created with '–no-site-packages'?
- Using existing field values in django update query
- Error loading MySQLdb module: libmysqlclient.so.20: cannot open shared object file: No such file or directory
- Creating UTF-8 JsonResponse in Django