django rest framework m2m更新方法

django rest framework m2m update method

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

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