简体   繁体   中英

Django: How to tell if an object has been updated after .save()

In Django 1.5, I'm using the following code to store some data into my models:

new_object, created = MyModel.objects.get_or_create(
    pk = object.id,
    default = object_dict
)

if created:
   # ... code that creates a log  ... 
else:
    newobject.save()
    # ... code that creates a log IF the record has been updated

As the save() method returns None, is there a way to know if the saved actually been updated without comparing the two states of the objects (before and after saving)?

get_or_create does not update, defaults is used for params that you do not want in the initial get query.

According to django docs:

defaults = kwargs.pop('defaults', {})
params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
params.update(defaults)
obj = self.model(**params)
obj.save()

The get_or_create method would not do an update to an existing database entry, thus calling newobject.save() would have no effect on the already created instance, if you did not manually set/change some of the instance properties. Also your get_or_create syntax is wrong, take a look at the docs . Note, it should be defaults instead of default.

new_object, created = MyModel.objects.get_or_create(
    pk=object.id,
    defaults=object_dict
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM