django admin在重写save_related时如何获取新对象的id

时间:2017-08-30 03:06:55

标签: django django-admin

我有下面的代码,我修改了管理表单以传递其他信息,然后在保存过程完成后使用。 使用保存按钮时,此工作正常。 以下代码的问题在于,当有人使用"另存为"按钮,sample_pk将是当前样本的id,而不是生成的新样本。 我的问题是如何在save_related上调用super之后获取新对象的id。

@admin.register(Sample)
class SampleAdmin(ModelAdmin):
    save_as = True
    def save_related(self, request, form, formsets, change):
        super(SampleAdmin, self).save_related(request, form, formsets, change)
        args = request.resolver_match.args
        if len(args) < 1: # not previously saved
            return
        sample_pk = int(args[0])
        new_things = []
        for formset in formsets:
            for key, val in formset.data.items():
                if key.startswith('robo_'):
                    new_things.append(val)
        x = sum(new_things)
        sam = Sample.objects.get(pk=sample_pk)
        OtherTable.objects.create(x=x, sample=sam)

1 个答案:

答案 0 :(得分:1)

我发现了。我应该用: 的 form.instance.id

@admin.register(Sample)
class SampleAdmin(ModelAdmin):
    save_as = True
    def save_related(self, request, form, formsets, change):
        super(SampleAdmin, self).save_related(request, form, formsets, change)
        args = request.resolver_match.args
        if len(args) < 1: # not previously saved
            return
        sample_pk = form.instance.id
        new_things = []
        for formset in formsets:
            for key, val in formset.data.items():
                if key.startswith('robo_'):
                    new_things.append(val)
        x = sum(new_things)
        sam = Sample.objects.get(pk=sample_pk)
        OtherTable.objects.create(x=x, sample=sam)