You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中ManyRelatedManager无save属性报错求助

问题:Django多对多关系保存时抛出'ManyRelatedManager' object has no attribute 'save'异常

使用Django基于模型的视图、表单和多态模型,在给Match模型的多对多字段添加对象后保存时出错。报错信息显示'ManyRelatedManager' object has no attribute 'save'。使用自动生成的中间表,注释掉报错的instance.tutor.save()行后,Match对象能正常包含表单选中的多对多字段内容,且中间表已添加对应值。

视图代码

if form.is_valid():

    instance = form.save(commit=False)
    current_user = self.request.user
    instance.lvm_affiliate = current_user.affiliate
    instance.save()

    if pt == 'tutor':
        person = Tutor.objects.get(id=pk)
        print("before ", vars(instance))
        print("student ", instance.student.all())
        print("tutor ", instance.tutor.all())
        instance.tutor.add(person.id)
        print("after ", vars(instance))
        print("student ", instance.student.all())
        print("tutor ", instance.tutor.all())
        instance.save()
        instance.tutor.save()

输出信息

before  {'_state': <django.db.models.base.ModelState object at 0x000001E84D5CEAA0>, 'id': 46, 'lvm_affiliate_id': 34, 'match_status_id': 3, 'date_started': datetime.date(2022, 7, 23), 'date_dissolved': None, 'comments': ''} 
student <PolymorphicQuerySet []> 
tutor  <PolymorphicQuerySet []> 
after {'_state': <django.db.models.base.ModelState object at 0x000001E84D5CEAA0>, 'id': 46, 'lvm_affiliate_id': 34, 'match_status_id': 3, 'date_started': datetime.date(2022, 7, 23), 'date_dissolved': None, 'comments': ''} 
student <PolymorphicQuerySet []> 
tutor  <PolymorphicQuerySet [<Tutor: joey>]>
Internal Server Error: /match/filter/9/tutor/

'ManyRelatedManager' object has no attribute 'save'

模型代码

class Match(models.Model):

    lvm_affiliate = models.ForeignKey(Affiliate, on_delete=models.SET_NULL, null=True,  blank=False)

    tutor = models.ManyToManyField(Tutor, blank=True, help_text="The tutor(s) associated with this match.")
    student = models.ManyToManyField(Student, blank=True, help_text="The student(s) associated with this match.")

解决方案

问题出在最后一行的instance.tutor.save()——instance.tutor是ManyRelatedManager对象,它没有save()方法。

Django中,当你通过add()方法给多对多字段添加关联对象时,这个操作会直接写入中间表,不需要额外调用Manager的save方法。只需要确保主对象instance已经被保存(你已经通过instance.save()完成了这一步),add()操作会自动持久化关联关系。

修改后的视图代码去掉多余的instance.tutor.save()即可:

if form.is_valid():

    instance = form.save(commit=False)
    current_user = self.request.user
    instance.lvm_affiliate = current_user.affiliate
    instance.save()

    if pt == 'tutor':
        person = Tutor.objects.get(id=pk)
        print("before ", vars(instance))
        print("student ", instance.student.all())
        print("tutor ", instance.tutor.all())
        instance.tutor.add(person.id)
        print("after ", vars(instance))
        print("student ", instance.student.all())
        print("tutor ", instance.tutor.all())
        instance.save()  # 主对象保存已足够,多对多关联通过add自动写入

补充:add()方法既可以接收对象实例,也可以接收主键ID,你这里用person.id是没问题的,也可以直接传person对象:instance.tutor.add(person),效果一致。


内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 18:18:29