0

我想用ManyToMany关系保存对象。当我提交表单时,除了有ManyToMany关系的字段之外,所有的东西都保存了。

这些是我的文件:

#Forms.py
class ExamForm(ModelForm):
    class Meta:
        model = Exam
        fields = '__all__'

#Models.py
class Exam(models.Model):
    questions = models.ManyToManyField(Question)
    title = models.CharField(max_length=250)
class Question(models.Model):
    title = models.CharField(max_length=250)
    answer = models.TextField(null=True, blank=True)

#Views.py
def add_exam(request):
    if request.method == "POST":
        form = ExamForm(request.POST)
        if form.is_valid():
            new_exam = form.save(commit=False)
            new_exam.save()
            return redirect('view_exam')
    else:
        form = ExamForm()
    template = 'add_exam.html'
    context = {'form': form}
    return render(request, template, context)

这些代码有什么问题?

4

1 回答 1

1

正如文档所解释的,当您使用commit=False表单时无法设置多对多关系,因为该对象还没有 ID。所以你需要调用表单的额外save_m2m()方法:

if form.is_valid():
    new_exam = form.save(commit=False) 
    # Add some modifications
    new_exam.save()
    form.save_m2m()
    return redirect('view_exam')

但是这里没有理由这样做。您不应该commit=False只使用然后立即保存模型。那是在您想要在保存之前修改对象时使用的,您在这里没有这样做。直接保存即可:

   if form.is_valid():
        form.save()
        return redirect('view_exam')
于 2019-08-08T07:19:11.200 回答