Copying Django model row data before updating

纵然是瞬间 提交于 2020-01-07 05:35:26

问题


Before updating a row, I'd like to save its current results into another table. Currently I am using pre_save but it does not seem to work as intended. It gives me updated data, not pre-updated data.

class Country(models.Model):
    name = models.CharField(max_length=16)

def make_copy(sender, **kwargs):
    obj = kwargs['instance']

pre_save.connect(make_copy, sender=Country)

If I change the country name from USA to Australia, for example, the obj.name in pdb will display the post-updated name of Australia rather than pre-updated name USA.

What am I missing?


回答1:


you would have to query the database to get the original object. instance has the updated object, which is ready to be saved into the database.

class Country(models.Model):
    name = models.CharField(max_length=16)

def make_copy(sender, **kwargs):
    obj = kwargs['instance']
    try:
        orig_obj = Country.objects.get(pk=obj.pk)
    except: #If it is a new object
        orig_obj = None

pre_save.connect(make_copy, sender=Country)



回答2:


The previous data only exists in the database; you will need to retrieve it in your handler.



来源:https://stackoverflow.com/questions/17076932/copying-django-model-row-data-before-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!