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 ..
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.
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