Better option to check if a particular instance exists django
An even better approach would be to use .exists()
to check if a particular instance exists or not.
MyObject.objects.filter(someField=someValue).exists() # return True/False
From the .exists()
docs:
It returns
True
if the QuerySet contains any results, andFalse
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.
Some examples from the docs:
Example-1: To find whether a model with unique field is a member of QuerySet
The most efficient method of finding whether a model with a uniquefield (e.g. primary_key) is a member of a QuerySet
is:
entry = Entry.objects.get(pk=123)if some_queryset.filter(pk=entry.pk).exists(): # faster print("Entry contained in queryset")
which will be faster than the following which requires evaluating anditerating through the entire queryset:
if entry in some_queryset: # slower print("Entry contained in QuerySet")
Example-2: Finding whether a queryset contains any items
To find whether a queryset contains any items, below method
if some_queryset.exists(): # faster print("There is at least one object in some_queryset")
will be faster than:
if some_queryset: # slower print("There is at least one object in some_queryset")
... but not by a large degree (hence needing a large queryset for efficiency gains).
What if i also want to use the object if it exists?
If you want to use the object also if it exists, then using .exists()
is not efficient as then you will perform 2 queries. First query will be to check for the existence and 2nd query will be to get the object.
I would say use the exists() on the filtered queryset like this,
MyObject.objects.filter(someField=someValue).exists()
The Django docs mostly encourage using exists(), instead of alternative methods. You can read more about this here.