I have some questions about django exists()
and DoesNotExist
exception.
Example code:
id = 1 # first if User.objects.get(pk=id).exists(): # my logic pass # second try: User.objects.get(pk=id) # my logic pass except User.DoesNotExist: return 0
I often use get()
method. Which practice is better? Which code is better? The first or second?
The DoesNotExist exception is raised when an object is not found for the given parameters of a query. Django provides a DoesNotExist exception as an attribute of each model class to identify the class of object that could not be found and to allow you to catch a particular model class with try/except.
Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.
if User.objects.get(pk=id).exists()
This won't work, so the question is pretty easy to answer: This way is inferior to the ways which do work :-)
I guess you actually didn't make a Minimal Complete Verifiable Example and so missed the error when you posted un-verified code.
So instead, I suppose you are asking about the difference between:
QuerySet.exists()
when you have a QuerySet (e.g. from a filter operation).
For example:
if User.objects.filter(pk=id).exists(): # ... do the things that need that user to exist
Model.objects.get(…)
and catching the Model.DoesNotExist
exception type (or, if you want to be more general, the parent type ObjectDoesNotExist
).
For example:
try: user = User.objects.get(pk=id) except User.DoesNotExist: # ... handle the case of that user not existing
The difference is:
The QuerySet.exists
method is on a queryset, meaning you ask it about a query (“are there any instances matching this query?”), and you're not yet attempting to retrieve any specific instance.
The DoesNotExist
exception for a model is raised when you actually attempted to retrieve one instance, and it didn't exist.
Use whichever one correctly expresses your intention.
You can find more info in docs: about exists()
,but exists()
works only for QuerySet
Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.
exists() is useful for searches relating to both object membership in a QuerySet and to the existence of any objects in a QuerySet, particularly in the context of a large QuerySet.
But ObjectDoesNotExist
works only with get()
.
Also you can try another approach:
user = User.objects.filter(id=2) if user: # put your logic pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With