如何强制将未更改的django实例添加到数据库

时间:2017-07-08 23:46:01

标签: python django django-models django-views

我正在开发一个网络应用程序,可以保存同一模型的真/假答案和多项选择答案(答案)

class Answer(models.Model):
    question = models.ForeignKey(Question, related_name='answers')
    correct = models.BooleanField()
    a_text = models.CharField(max_length=255, null=True, blank=True)
    created = models.DateTimeField(auto_now_add="True")

每当我保存到模型时,我都会删除该模型的现有数据,并打算从实例 request.POST

中的数据重新填充该数据

然后我在Django文档中读到了

save()方法返回已保存到数据库的实例。如果绑定数据中给定实例的数据未更改,则实例将不会保存到数据库,并且不会包含在返回值中(实例) ,在上面的例子中。

请帮忙,我被困住了。

这是我的表格声明

class AnswerForm(ModelForm):
    class Meta:
        model = Answer
        fields = ['a_text', 'correct']
        widgets = {
            'correct': RadioSelect(choices=[(True, "True"), (False, "False")])
        }

AnswerFormSet = modelformset_factory(
    Answer,
    fields = ('a_text', 'correct'),
    max_num = 4,
    min_num = 4 )

这是我的观点

def create_question(request, quiz_id, que_id=None):
    quiz = get_object_or_404(Quiz, id=quiz_id)
    created_questions = Question.objects.filter(quiz=quiz_id)

    if que_id:
        que_id = int(que_id)
        que = get_object_or_404(Question, id=que_id, quiz=quiz)

        question_form = QuestionForm(instance=que)

        if que.question_type == 'multiplechoice':
            multiple_choice_answer_form = AnswerFormSet(
                                            queryset=que.answers.all(), 
                                            )
            truefalse_answer_form = AnswerForm()
        elif que.question_type == 'truefalse':
            multiple_choice_answer_form = AnswerFormSet(
                                            queryset=que.answers.none(), 
                                            )
            for ans_form in que.answers.all():
                truefalse_answer_form = AnswerForm(instance=ans_form)


    else:
        question_form = QuestionForm()
        truefalse_answer_form = AnswerForm()
        multiple_choice_answer_form = AnswerFormSet(queryset=Answer.objects.none())

    if request.method == 'POST':
        # import pdb; pdb.set_trace(); 
        if que_id:
            question_form = QuestionForm(instance=que, data=request.POST, files=request.FILES)
            if que.question_type == 'multiplechoice':
                multiple_choice_answer_form = AnswerFormSet(
                                                data=request.POST,
                                                queryset=que.answers.all())
                truefalse_answer_form = AnswerForm(data=request.POST)

            elif que.question_type == 'truefalse':
                multiple_choice_answer_form = AnswerFormSet(data=request.POST, queryset=que.answers.none())
                for ans_form in que.answers.all():
                    truefalse_answer_form = AnswerForm(data=request.POST, instance=ans_form)

        else:
            question_form = QuestionForm(data=request.POST, files=request.FILES)
            truefalse_answer_form = AnswerForm(request.POST)
            multiple_choice_answer_form = AnswerFormSet(request.POST, queryset=que.answers.all())

        if question_form.is_valid() and truefalse_answer_form.is_valid() and multiple_choice_answer_form.is_valid():

            question = question_form.save(commit=False)
            question.quiz = quiz
            question.save()

            que_type = question_form['question_type'].data


            if que_type == 'truefalse':

                # delete existing data to avoid mixing the True/False and Multiple choice answers
                if que_id:
                    for q in que.answers.all():
                        q.delete()

                truefalse = truefalse_answer_form.save(commit=False)
                truefalse.question = question
                truefalse.save()
            elif que_type == 'multiplechoice':

                multiple_choice = multiple_choice_answer_form.save(commit=False)            
                for multiple_choice_que in multiple_choice:
                    multiple_choice_que.question = question
                    multiple_choice_que.save()



            if 'save' in request.POST:
                print('Saving and Redirecting to edit Section...')
                messages.success(request, 'Question saved successfully!')
                return redirect('edit_question', quiz_id=quiz_id, que_id=question.id)

            elif 'add_new' in request.POST:
                question_form = QuestionForm()
                truefalse_answer_form = AnswerForm()
                messages.success(request, 'Question added successfully!')
                print("Add new question")

                return redirect('create_question', quiz_id=quiz_id)
        else:
            messages.error(request, 'An error was encountered!')

    return render(request, 'quiz/question/create.html', {'question_form': question_form,
                                                            'quiz': quiz,
                                                            'que_id': que_id,
                                                            'created_questions': created_questions,
                                                            'multiple_choice': multiple_choice_answer_form,
                                                            'truefalse': truefalse_answer_form })

1 个答案:

答案 0 :(得分:0)

我能够通过在我的模型中创建另一个Field来获得我的问题的解决方案,我通过检查额外的模型字段(如果为true或false)删除了之前的问题对象。