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?
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.
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.
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() .
TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.
If you save your instance through a form, you can check form.has_changed()
.
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