I've got a code like that:
# ...
obj = Model.objects.get(pk=2342)
if foo:
obj.foo = 'bar'
if bar:
obj.bar = 'baz'
obj.save()
Is there a good way to find out if the model instance was modified in order to prevent saving it each time the code runs?
Use the has_changed() method on your Form when you need to check if the form data has been changed from the initial data.
Then in save method you can compare old and new value of field to check if the value has changed. @classmethod def from_db(cls, db, field_names, values): new = super(Alias, cls). from_db(db, field_names, values) # cache value went from the base new. _loaded_remote_image = values[field_names.
def __str__( self ): return "something" This will display the objects as something always in the admin interface. Most of the time we name the display name which one could understand using self object. For example return self.
The typical pattern is to do something like:
model = Model.objects.get(pk=2342)
dirty = False
if foo:
model.foo = 'bar'
dirty = True
if bar:
model.bar = 'baz'
dirty = True
if dirty:
model.save()
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