When I ask the model manager to get an object, it raises DoesNotExist when there is no matching object.
go = Content.objects.get(name="baby")
Instead of DoesNotExist, how can I have go be None instead?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is no ‘built in’ way to do this. Django will raise the
DoesNotExistexception every time.The idiomatic way to handle this in python is to wrap it in a try catch:
What I did do, is to subclass
models.Manager, create asafe_getlike the code above and use that manager for my models. That way you can write:SomeModel.objects.safe_get(foo='bar').