Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know if django model instance was modified?

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?

like image 323
Ivan Ivanov Avatar asked May 02 '12 12:05

Ivan Ivanov


People also ask

What method can you use to check if from data has been changed when using a form instance?

Use the has_changed() method on your Form when you need to check if the form data has been changed from the initial data.

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

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.

What is def __ str __( self in Django model?

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.


1 Answers

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()
like image 108
Chris Pratt Avatar answered Sep 23 '22 00:09

Chris Pratt