我是 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 方法中使用深度复制,但是得到 “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()
感谢您提前提供的帮助。
最佳答案
最终放弃了 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()
关于python - Django - 复制具有 2 个嵌套外键的模型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28468428/