我有以下模型,我在admin.py中使用'save_as'来启用管理员更改表单上的“另存为新功能”。
目标是如果我使用'save_as',“旧”对象应该将布尔字段'hide'设置为True。
我尝试将ModelAdmin方法'save_model'实现为admin.py,但这只会更改“new”对象的值。
是否可以更改“旧”对象?
models.py
class Person(models.Model):
name = models.CharField(max_length=64)
hide = models.BooleanField(default=0)
admin.py
class personAdmin(admin.ModelAdmin):
save_as = True
def save_model(self, request, obj, form, change):
obj.hide = True
super(personAdmin, self).save_model(request, obj, form, change)
答案 0 :(得分:2)
试试这个:
def save_model(self, request, obj, form, change):
# Get old object's id from the url
old_obj_id = resolve(request.path).args[0]
# Now that we know the id, we can easily fetch it from database
old_obj = Person.objects.get(id=old_obj_id)
# Update it's hide field
old_obj.hide = True
# Don't forget to save it!
old_obj.save()
# Now we can save the new object as a new one (save_as)
super(personAdmin, self).save_model(request, obj, form, change)