Search code examples
djangomany-to-manydjango-serializer

Django ManyToMany | TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use course_tags.set() instead


My model:

class Course(models.Model):
    ...
    course_tags = models.ManyToManyField(CourseTag, related_name='course_tags', blank=True)
    ...

My Serializer:

class CourseSerializer(serializers.ModelSerializer):
    ...
    course_tags = CourseTagsSerializer(many=True, required=False)
    ...
    class Meta:
        model = Course
        fields = [...'course_tags'...]

    def create(self, validated_data):
        ...
        tags_data = validated_data.pop('tags', None)
        ...
        course, _ = Course.objects.create(
            author=author, **validated_data)

        if tags_data:
            for tag in tags_data:
                new_tag, _ = CourseTag.get_or_create(title=tag.get('title'))
                course.course_tags.add(new_tag.id)
        course.save()

I'm sending POST request to this serializer. Response:

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

I tried working method but, my code is not working.


Solution

  • Field is names course_tags so you should use this name when you fetch tags from validated data:

    def create(self, validated_data):
        ...
        tags_data = validated_data.pop('course_tags', None)
    

    Otherwise course_tags is still in validated_data and Course.objects.create() raises the error.