Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a model has changed before calling save in Django

Tags:

I have a database model that is being updated based on changes in remote data (via an HTML scraper).

I want to maintain a field called changed - a timestamp denoting when the last time that model's values changed from what they were previously (note that this is different from auto_now as these fields are updated every time a model's save method is called).

Here is my question:

In a model's save method, is there a straightforward way to detect if a model instance's current values are different from the values in the database? Or, are there any alternative methods to easily maintain a changed timestamp?

like image 473
advait Avatar asked Mar 09 '11 02:03

advait


People also ask

When saving How can you check if a field has changed Django?

To check if a field has changed when saving with Python Django, we can override the `init method of the model class to keep a copt of the original value. to add the __init__ method that sets the __original_name variable to self.name to keep the original name value.

What is Manytomanyfield in Django?

A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.

How do I save changes in Django model?

Saving changes to objects 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() .

What is timestamped model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.


1 Answers

If you save your instance through a form, you can check form.has_changed().

like image 199
Don Avatar answered Oct 18 '22 21:10

Don