Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you detect a new instance of the model in Django's model.save() [duplicate]

Tags:

While overriding the specific model's save() method, Is it possible determine whether it's a new record or an update?

like image 949
Sivasubramaniam Arunachalam Avatar asked Jan 01 '11 14:01

Sivasubramaniam Arunachalam


People also ask

What does save () do in Django?

To save changes to an object that's already in the database, use save() . This performs an UPDATE SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() .

How do I create an instance of a Django model?

To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .

What is __ Str__ in Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this. Note: how objects are just plainly numbered. to this.

How do I save changes in Django model?

save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database. update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.


1 Answers

If self.pk is None it is a new record.

def save(self):     if self.pk is None:         self.created = datetime.today()     self.modified = datetime.today()     super(ProjectCost, self).save() 

This topic has been discussed also here

like image 169
Thomas Kremmel Avatar answered Oct 15 '22 11:10

Thomas Kremmel