Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the canonical way to find out if a Django model is saved to db?

I generally check if obj.pk to knwo if the objects is saved. This wont work however, if you have primary_key = True set on some fields. Eg I set user = models.OneToOneField(User, primary_key=True) on my UserProfile.

What is the canonical way to find out if a Django model is saved to db?

like image 535
agiliq Avatar asked Jan 10 '10 14:01

agiliq


People also ask

Which method is used to save a model in DB in Python Django?

The save method is an inherited method from models. Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run.

How does Django save data to database?

Creating objectsTo 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.


1 Answers

Nowadays you can check for:

self._state.adding 

This value is set by the QuerySet.iterator() for objects which are not added yet in the database. You can't use this value in the __init__() method yet, as it's set after the object is constructed.

like image 194
vdboor Avatar answered Oct 06 '22 00:10

vdboor