【问题标题】:Django - Copying a model instance with 2 nested foreignkeysDjango - 使用 2 个嵌套外键复制模型实例
【发布时间】:2015-02-12 02:49:10
【问题描述】:

我是 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 约束失败: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()

提前感谢您的帮助。

【问题讨论】:

    标签: python django django-admin


    【解决方案1】:

    最终放弃了 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      相关资源
      最近更新 更多