56👍
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 unique
field (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 and
iterating 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.
0👍
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.
- [Django]-Related_name argument not working as expected in Django model?
- [Django]-How can I get 'pk' or 'id' in `get_context_data` from CBV?
- [Django]-How to update() a single model instance retrieved by get() on Django ORM?
0👍
It depends on you want to get one record or many
One need to include them in try and except blocks if you need to check existence in a pythonic way
try:
instance = MyModel.objects.all().get(condition)
#can continue to use instance
except MyModel.DoesNotExist:
#do something if model does not exist
Print(“model instances doesn't exist”)
If you’re using a filter or for getting all instances
instances = MyModel.objects.all().filter(condition)
If instances:
#if list of instances have Atleast one instance
Pass
else:
#do something if model does not exist
Print(“model instances doesn't exist”)
- [Django]-Page not found 404 Django media files
- [Django]-ImportError: cannot import name 'six' from 'django.utils'
- [Django]-How do I use pagination with Django class based generic ListViews?