更新前复制Django模型行数据 [英] Copying Django model row data before updating
问题描述
在更新行之前,我想将其当前结果保存到另一个表中。目前我正在使用pre_save,但似乎没有按预期工作。它给我更新的数据,而不是预先更新的数据。
class国家(models.Model):
name = models.CharField(max_length = 16)
def make_copy(sender,** kwargs):
obj = kwargs ['instance']
pre_save.connect make_copy,sender = Country)
如果我将国家名称从美国更改为澳大利亚,例如pdb中的obj.name将显示澳大利亚的更新名称,而不是预先更新的名称美国。
我缺少什么?
您将不得不查询数据库以获取原始对象。 实例
具有更新的对象,可以将其保存到数据库中。
class国家(models.Model):
/ pre>
name = models.CharField(max_length = 16)
def make_copy(sender,** kwargs):
obj = kwargs ['instance']
try:
orig_obj = Country.objects.get(pk = obj.pk)
除了:#如果它是一个新对象
orig_obj =无
pre_save.connect(make_copy,sender = Country)
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?
解决方案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)
这篇关于更新前复制Django模型行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!