Reputation: 9136
What is the best way to get an object which is not sure if there is or not.(in Django model)
I think there are three options.
One is to use try
and except
statement to process the exception.
Second is to use objects.filter()
instead of objects.get()
and check query_set.count()
.
Third is to use objects.count()
first and then use objects.get()
if there is.
Upvotes: 1
Views: 51
Reputation: 2569
Edited: I think the best solution in this case, is use this third package
django-annoying
This packaged contains a lot of syntactic sugar for things like that.
With this package, you can use the function get_object_or_None
, similar to
get_object_or_404.
But, the real code behind this function is :
def get_object_or_None(klass, *args, **kwargs):
"""
Uses get() to return an object or None if the object does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(), a MultipleObjectsReturned will be raised if more than one
object is found.
"""
queryset = _get_queryset(klass)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
return None
Note: Don’t use this if all you want to do is determine if at least one result exists. It’s more efficient to use exists().
Upvotes: 1
Reputation: 47846
You can use .first()
operation on a queryset to your advantage to get the first object of the queryset if it exists and None
otherwise.
Returns the first object matched by the queryset, or None if there is no matching object.
my_object = some_queryset.first() # return a object or 'None'
This will return the first object of the queryset if there are objects in the queryset. Otherwise, it returns None
. It will automatically handle the case when objects do no exist without you needing to write try-except
.
The above code is equivalent to writing:
try:
my_object = some_queryset[0] # access the first element
except IndexError:
my_object = None
Note: Here, we needed the object, so we are using .first()
. If we needed to check only if the object exists, then we could have used .exists()
Upvotes: 1