2

I have a couple of m2m fields in my serializer that I need to save on update. My create() method functions fine, however I get the following error with my code:

Django :: 2.0.1 DRF :: 3.7.7

Direct assignment to the forward side of a many-to-many set is prohibited. Use advice_areas.set() instead.

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

This used to work, and I'm unsure why it isn't now.

Any help would be appreciated.

Abbreviated models:

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

Abbreviated serializer:

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

1 Answers1

4

You have issue while setting ManyToManyField. save it using add method

for attr, value in validated_data.items():
    if str(attr) != 'advice_areas':
       setattr(instance, attr, value)
    else:
       instance.advice_areas.add(value)
instance.save()
Satendra
  • 6,755
  • 4
  • 26
  • 46