13π
This isnβt the best practice. You can technically do this without using exceptions. Did you intend to use Location
and Car
in this example?
You can do this:
Location.objects.filter(name='Paul').order_by('id').first()
I strongly suggest you read the Django QuerySet API reference.
https://docs.djangoproject.com/en/1.8/ref/models/querysets/
To answer your question about where the exception exists β you can always access these QuerySet exceptions on the model itself. E.g. Location.DoesNotExist
and Location.MultipleObjectsReturned
. You donβt need to import them if you already have the model imported.
57π
Use a filter:
Location.objects.filter(name='Paul').first()
Or import the exception:
from django.core.exceptions import MultipleObjectsReturned
...
try:
Location.objects.get(name='Paul')
except MultipleObjectsReturned:
Location.objects.filter(name='Paul').first()
- [Django]-How to set-up a Django project with django-storages and Amazon S3, but with different folders for static files and media files?
- [Django]-How to set True as default value for BooleanField on Django?
- [Django]-Get count of related model efficiently in Django
48π
This is more pythonic way to do it.
try:
Location.objects.get(name='Paul')
except Location.MultipleObjectsReturned:
Location.objects.filter(name='Paul')[0]
- [Django]-Django: How to access original (unmodified) instance in post_save signal
- [Django]-Strings won't be translated in Django using format function available in Python 2.7
- [Django]-Bulk create model objects in django
5π
Use get when you know there is only one object that matches your query. If no items match the query, get() will raise a DoesNotExist exception. If multiple items matches the query, get() will raise a MultipleObjectsReturned exception. Use get() like this:
try:
one_entry = Entry.objects.get(blog=2000)
except Entry.DoesNotExist:
# query did not match to any item.
pass
except Entry.MultipleObjectsReturned:
# query matched multiple items.
pass
else:
# query matched to just one item
print(one_entry)
- [Django]-What is the purpose of NGINX and Gunicorn running in parallel?
- [Django]-Max image size on file upload
- [Django]-How do I raise a Response Forbidden in django
3π
Actually, even if we use MyModel.objects.get_or_create(...)
, there is still chances for creation of multiple instances due to race conditions. So, when we have to use MyModel.objects.get
or MyModel.objects.get_or_create
, we still have to expect return of multiple objects.
To handle this:
from django.core.exceptions import MultipleObjectsReturned
try:
obj,is_created=MyModel.objects.get_or_create(....)
except MultipleObjectsReturned as e:
# handle the case as you need here
pass
- [Django]-Django: When to use QuerySet none()
- [Django]-Using mock to patch a celery task in Django unit tests
- [Django]-How to run this code in django template