2015-02-12 63 views
2

我是django的新手,我有一个调查应用程序,其中管理员创建有问题的调查,问题有选择...我已将save_as = True添加到我的调查管理员,但是当我复制一个调查,问题是存在于副本,而不是选择..Django - 使用2个嵌套外键复制模型实例

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。是否有更好的方式通过管理员复制调查,或者我可以如何修复我的深度复制应用程序?

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

感谢您提前给予的帮助。

回答

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