When I ask the model manager to get an object, it returns DoesNotExist since no such object exists.
go = Content.objects.get(name="baby")
Instead of DoesNotExist, how can I have go be None instead?
Asked by TIMEX
There isn’t a ‘built-in’ technique to accomplish this. Django will always throw the DoesNotExist exception. In Python, the customary approach to deal with this is to encapsulate it in a try catch:
try: go = SomeModel.objects.get(foo='bar') except SomeModel.DoesNotExist: go = None
I did, however, subclass models. Create a safe get like the code above and use that manager for my models, manager. You can write: SomeModel.objects.safe get(foo=’bar’) in this way.
Answered by Arthur Debert
Since Django 1.6, you can utilize the first() function in the following way:
Answered by FeroxTL
From django docs
You can catch the exception and assign None to go.
from django.core.exceptions import ObjectDoesNotExist try: go = Content.objects.get(name="baby") except ObjectDoesNotExist: go = None
Answered by Amarghosh
This can be done with a generic function.
def get_or_none(classmodel, **kwargs): try: return classmodel.objects.get(**kwargs) except classmodel.DoesNotExist: return None
Use it as follows:
go = get_or_none(Content,name="baby")
going to be If no entry matches, nothing is returned; otherwise, the Content entry is returned.
Note:It will raises exception MultipleObjectsReturned if more than one entry returned for name=”baby”.
To avoid this type of issue, you should handle it on the data model, although you may want to log it at run time like this:
def get_or_none(classmodel, **kwargs): try: return classmodel.objects.get(**kwargs) except classmodel.MultipleObjectsReturned as e: print('ERR====>', e) except classmodel.DoesNotExist: return None
Answered by Ranju R
This is how you can go about it:
go = Content.objects.filter(name="baby").first()
Now either the object you want or None can be used as the go variable.
Answered by Gaurav
Post is based on https://stackoverflow.com/questions/3090302/how-do-i-get-the-object-if-it-exists-or-none-if-it-does-not-exist-in-django