【问题标题】:django rest framework m2m update methoddjango rest框架m2m更新方法
【发布时间】:2018-06-18 06:56:25
【问题描述】:

我的序列化程序中有几个 m2m 字段需要在更新时保存。我的 create() 方法运行良好,但是我的代码出现以下错误:

Django :: 2.0.1 DRF :: 3.7.7

禁止直接分配到多对多集合的前端。请改用advice_areas.set()。

def update(self, instance, validated_data):
    if instance.name != validated_data['name']:
        instance.url_name = slugify(validated_data['name'])
    if instance.postcode != validated_data['postcode']:
        validated_data['location'] = geo(validated_data['postcode'])
    for attr, value in validated_data.items():
        setattr(instance, attr, value)
    instance.save()

    return instance

这曾经有效,但我不确定为什么现在无效。

任何帮助将不胜感激。

缩略型号:

class Practice(models.Model):
    owner = models.OneToOneField(User, on_delete=models.CASCADE,
                             help_text='User account that owns this practice')
    name = models.CharField(max_length=200, verbose_name='Practice Name')
    advice_areas = models.ManyToManyField(AdviceArea, verbose_name='Areas of advice')

class AdviceArea(models.Model):
    name = models.CharField(max_length=255, null=False, blank=False, unique=True)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.name

缩写序列化器:

class PracticeSerializer(serializers.HyperlinkedModelSerializer):
    advice_areas = serializers.HyperlinkedRelatedField(
    many=True, view_name='advicearea-detail', queryset=AdviceArea.objects.all())

【问题讨论】:

  • 也发布你的模型

标签: django rest django-rest-framework manytomanyfield m2m


【解决方案1】:

您在设置 ManyToManyField 时遇到问题。使用add方法保存

for attr, value in validated_data.items():
    if str(attr) != 'advice_areas':
       setattr(instance, attr, value)
    else:
       instance.advice_areas.add(value)
instance.save()

【讨论】:

  • 感谢您的帮助,仍然无法正常工作。它返回 save() 得到了一个意外的关键字参数 'commit'
  • @user1496093 直接保存M2M字段有问题,查看我的更新答案
  • 谢谢萨滕德拉。我不得不将 .add 更改为 .set 并且它起作用了!非常感谢。
猜你喜欢
  • 2020-05-30
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 2016-08-09
相关资源
最近更新 更多