Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Get an object form the DB, or 'None' if nothing matches

Tags:

python

django

Is there any Django function which will let me get an object form the database, or None if nothing matches?

Right now I'm using something like:

foo = Foo.objects.filter(bar=baz) foo = len(foo) > 0 and foo.get() or None 

But that's not very clear, and it's messy to have everywhere.

like image 972
David Wolever Avatar asked Oct 02 '09 22:10

David Wolever


People also ask

How can I get objects in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

Is not exist Django?

ObjectDoesNotExist and DoesNotExistDjango provides a DoesNotExist exception as an attribute of each model class to identify the class of object that could not be found and to allow you to catch a particular model class with try/except .


1 Answers

There are two ways to do this;

try:     foo = Foo.objects.get(bar=baz) except model.DoesNotExist:     foo = None 

Or you can use a wrapper:

def get_or_none(model, *args, **kwargs):     try:         return model.objects.get(*args, **kwargs)     except model.DoesNotExist:         return None 

Call it like this

foo = get_or_none(Foo, baz=bar) 
like image 167
Nick Craig-Wood Avatar answered Sep 30 '22 11:09

Nick Craig-Wood