Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get_object_or_404 or filter exists

We need to identify the object is available in model or not.

There are two methods are available to check if exists ,

MyModel.objects.filter(pk=pk).exists()

or

get_object_or_404(MyModel, pk=pk)

Which query is better and efficient ?

Note: No need to perform any actions using that object(pk). Just want to know if exists or not ..

like image 351
Muthuvel Avatar asked Apr 09 '16 09:04

Muthuvel


1 Answers

Using

get_object_or_404(MyModel, pk=pk)

is a shortcut for

try:
    my_model = MyModel.objects.get(pk=pk)
except:
    raise Http404

Therefore you should only use get_object_or_404 if you want to return a 404 error when the object doesn't exist.

If you don't actually need the model object, then in theory it would be more efficient to use exists() instead of get(), because exists() doesn't actually return the object:

if not MyModel.objects.exists():
    raise Http404

In practice, I'm not sure whether you would actually notice the difference. Therefore you might choose to use get_object_or_404 to make the code slightly simpler.

like image 173
Alasdair Avatar answered Nov 15 '22 21:11

Alasdair