问题
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