2015-02-12 124 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()