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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With