简体   繁体   English

复制/克隆Django模型

[英]Copy/clone Django Model

I am trying to make a copy of this model 我正在尝试复制此模型

class Quiz(models.Model):

title = models.CharField(
    verbose_name=_("Title"),
    max_length=60, blank=False)

description = models.TextField(
    verbose_name=_("Description"),
    blank=True, help_text=_("a description of the quiz"))

url = models.SlugField(
    max_length=60, blank=False,
    help_text=_("a user friendly url"),
    verbose_name=_("user friendly url"))

category = models.ForeignKey(
    Category, null=True, blank=True,
    verbose_name=_("Category"))

random_order = models.BooleanField(
    blank=False, default=False,
    verbose_name=_("Random Order"),
    help_text=_("Display the questions in "
                "a random order or as they "
                "are set?"))

max_questions = models.PositiveIntegerField(
    blank=True, null=True, verbose_name=_("Max Questions"),
    help_text=_("Number of questions to be answered on each attempt."))

answers_at_end = models.BooleanField(
    blank=False, default=False,
    help_text=_("Correct answer is NOT shown after question."
                " Answers displayed at the end."),
    verbose_name=_("Answers at end"))

exam_paper = models.BooleanField(
    blank=False, default=False,
    help_text=_("If yes, the result of each"
                " attempt by a user will be"
                " stored. Necessary for marking."),
    verbose_name=_("Exam Paper"))

single_attempt = models.BooleanField(
    blank=False, default=False,
    help_text=_("If yes, only one attempt by"
                " a user will be permitted."
                " Non users cannot sit this exam."),
    verbose_name=_("Single Attempt"))

pass_mark = models.SmallIntegerField(
    blank=True, default=0,
    verbose_name=_("Pass Mark"),
    help_text=_("Percentage required to pass exam."),
    validators=[MaxValueValidator(100)])

success_text = models.TextField(
    blank=True, help_text=_("Displayed if user passes."),
    verbose_name=_("Success Text"))

fail_text = models.TextField(
    verbose_name=_("Fail Text"),
    blank=True, help_text=_("Displayed if user fails."))

draft = models.BooleanField(
    blank=True, default=False,
    verbose_name=_("Draft"),
    help_text=_("If yes, the quiz is not displayed"
                " in the quiz list and can only be"
                " taken by users who can edit"
                " quizzes."))

Basically this is a quiz. 基本上,这是一个测验。 It has its own questions which can be added in the django admin. 它有自己的问题,可以在django管理员中添加。 Now when I make a copy of this model the questions for the copy aren't there. 现在,当我复制此模型时,副本的问题就不存在了。

I make a copy by using this. 我用这个做一个副本。

Obj=Quiz.objects.get(pk=pkofquiziwanttocopy)
Obj.pk=None
Obj.save()

This makes a copy of the quiz but the questions arent there. 这将构成测验的副本,但在那里没有问题。 Now there is some code in the admin.py regarding the qurstions for the quiz. 现在,admin.py中有一些有关测验问题的代码。 Which might be helpful. 这可能会有所帮助。

class QuizAdminForm(forms.ModelForm):
"""
below is from
https://stackoverflow.com/questions/11657682/
django-admin-interface-using-horizontal-filter-with-
inline-manytomany-field
"""

class Meta:
    model = Quiz
    exclude = []

questions = forms.ModelMultipleChoiceField(
    queryset=Question.objects.all().select_subclasses(),
    required=False,
    label=_("Questions"),
    widget=FilteredSelectMultiple(
        verbose_name=_("Questions"),
        is_stacked=False))

def __init__(self, *args, **kwargs):
    super(QuizAdminForm, self).__init__(*args, **kwargs)
    if self.instance.pk:
        self.fields['questions'].initial =\
            self.instance.question_set.all().select_subclasses()

def save(self, commit=True):
    quiz = super(QuizAdminForm, self).save(commit=False)
    quiz.save()
    quiz.question_set = self.cleaned_data['questions']
    self.save_m2m()
    return quiz

How can I make a copy of this model with the questions of the original ? 我该如何复制带有原始问题的模型?

Assuming, the Question model has a foreign key to Quiz , you can clone the questions just like you cloned the quiz: 假设, Question模型具有Quiz的外键,您可以像克隆测验一样克隆问题:

quiz = Quiz.objects.get(pk=pkofquiziwanttocopy)
quiz.pk = None
quiz.save()
old_quiz = Quiz.objects.get(pk=pkofquiziwanttocopy)
for quest in old_quiz.question_set.all():
    quest.pk = None
    quest.quiz = quiz
    quest.save()

What ended up being the solution is: 最终成为解决方案的是:

quiz = Quiz.objects.get(pk=pkofquiziwanttocopy)
quiz.pk = None
quiz.save()
old_quiz = Quiz.objects.get(pk=pkofquiziwanttocopy)

quiz.question_set=old_quiz.question_set.all()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM