Django - 使用 2 个嵌套外键复制模型实例

Django - Copying a model instance with 2 nested foreignkeys

我是 django 的新手,我有一个调查应用程序,管理员可以在其中创建有问题的调查,这些问题有选择......我已经将 save_as = True 添加到我的调查管理员,但是当我复制调查问卷时,问题出现在副本中,但选项没有..

class SurveyAdmin(admin.ModelAdmin):
    save_as = True
    prepopulated_fields = { "slug": ("name",),}
    fields = ['name', 'insertion', 'pub_date', 'description', 'external_survey_url', 'minutes_allowed', 'slug']
    inlines = [QuestionInline, SurveyImageInLine]

我试图在 save_model 方法中使用 deepcopy,但是得到 "NOT NULL constraint failed: assessment_question.survey_id",从回溯来看,似乎在尝试保存时问题的 pk 是 None。有没有更好的方法通过管理员复制调查,或者如何修复我的 deepcopy 应用程序?

def save_model(self, request, obj, form, change):
    if '_saveasnew' in request.POST:
        new_obj = deepcopy(obj)
        new_obj.pk = None
        new_obj.save()

提前感谢您的帮助。

最终放弃了 save_as 并编写了一个管理操作来正确复制我需要的所有字段...

actions = ['duplicate']

from copy import deepcopy

def duplicate(self, request, queryset):
    for obj in queryset:
        obj_copy = deepcopy(obj)
        obj_copy.id = None
        obj_copy.save()

        for question in obj.question_set.all():
            question_copy = deepcopy(question)
            question_copy.id = None
            question_copy.save()
            obj_copy.question_set.add(question_copy)

            for choice in question.choice_set.all():
                choice_copy = deepcopy(choice)
                choice_copy.id = None
                choice_copy.save()
                question_copy.choice_set.add(choice_copy)
        obj_copy.save()