Django - Copying a model instance with 2 nested fo

2019-05-22 02:25发布

问题:

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]

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

Thank you for your help in advance.

回答1:

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