关于django:’save_model’方法+’save_as = True’//如何更改“旧”对象

'save_model' method + 'save_as = True' // how to change “old” object

我有以下模型,我在admin.py中使用"另存为"在管理更改表单上启用"另存为新"功能。

目标是,如果我使用"另存为",则"old"对象应该将布尔字段"hide"设置为true。

我尝试将model admin方法"save_model"实现为admin.py,但这只会更改"new"对象的值。

是否也可以更改"旧"对象?

模特儿

1
2
3
class Person(models.Model):
    name = models.CharField(max_length=64)
    hide = models.BooleanField(default=0)

行政管理部门

1
2
3
4
5
6
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)

试试这个:

1
2
3
4
5
6
7
8
9
10
11
12
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)