Django - 使用2个嵌套外键复制模型实例 [英] Django - Copying a model instance with 2 nested foreignkeys

查看:125
本文介绍了Django - 使用2个嵌套外键复制模型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是django的新手,我有一个调查应用程序,其中管理员创建有问题的调查问题有选择...我已经添加了save_as = True给我的调查管理员,但是当我复制一个调查,问题出现在副本中,但不是选项。

I am new to django and I have an Survey app in which the admin creates surveys which have questions, the questions have choices... I have added the save_as = True to my survey admin, however when I copy a survey, the questions are present in the copy, but not the choices..

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。有没有更好的方法来通过管理员复制调查问卷,或者如何修复我的深层复制应用程序?

I have attempted to make use of deepcopy in the save_model method, but get "NOT NULL constraint failed: assessment_question.survey_id", from the traceback, it appears that the pk of the question is None when attempting to save. Is there a better way to copy the surveys through the admin or how can I fix my application of 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,并写了一个管理操作,正确地复制了我需要的所有字段。

Ended up ditching save_as all together and wrote an admin action that properly copies all the fields I need...

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()

这篇关于Django - 使用2个嵌套外键复制模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆