Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model.objects.get() or None

Is there a way to accomplish the following in one call:

Model.objects.get(id=1) else None 

The only way I've found a way to do this is by doing:

try:     object = Model... except:     object = None 

Is there a way to do this in a single call in django?

Update: There does not seem to be a way to do this other than in a try/except block, but here is a better answer: In Django, how do I objects.get, but return None when nothing is found?

like image 344
David542 Avatar asked Jun 03 '12 01:06

David542


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.

Why are QuerySets considered lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.

What is a QuerySet?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


1 Answers

How about this:

obj = Model.objects.filter(id=1).first() 

now if no object with id=1 exists obj would be None

Ref: https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.query.QuerySet.first

like image 157
Gaurav Avatar answered Sep 21 '22 00:09

Gaurav