django rest框架m2m更新方法

时间:2018-01-09 09:18:10

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

我的序列化程序中有几个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())

1 个答案:

答案 0 :(得分:4)

设置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()