Abdul Rehman Abdul Rehman - 3 months ago 7
Python Question

Object.get() throws exception if Nothing is found

Is there a possibility to return none if no results are found by a

object.get()
function call?
I know it throws an exception by default, but I want to return none from it.

Answer

You can do it with exceptions like:

 try:    
     object = Model.objects.get(foo='bar') 
 except Model.DoesNotExist:    
     object = None