【问题标题】:Save everything for new object except ManyToMany field in Django保存新对象的所有内容,除了 Django 中的 ManyToMany 字段
【发布时间】:2019-08-07 21:10:14
【问题描述】:

我想用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)

这些代码有什么问题?

【问题讨论】:

  • new_exam.save_m2m()?

标签: python django django-models many-to-many django-2.2


【解决方案1】:

正如docs 解释的那样,当您使用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')

【讨论】:

  • 谢谢它有效。但是在保存之前添加一些修改对象呢?例如,如果我需要设置 form.save(commit=False) 并添加以下行:` if 'is_allow_cmets' in request.POST: new_exam.is_allow_cmets = True else: new_exam.is_allow_cmets = False ;我应该做什么 ? @丹尼尔-罗斯曼
  • 正如我所说,那是你在new_exam.save() 之后执行form.save_m2m() 的时候。见the docs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
  • 2018-12-07
  • 2012-03-08
  • 1970-01-01
  • 2012-06-22
  • 2014-03-31
相关资源
最近更新 更多