在序列化程序中创建具有多对多字段的模型时出现问题

Problem with creation of model with many-to-many field in serializer

我有 CourseTeacherProfileStudentProfile 模型具有以下关系:

class Course(models.Model):
    students = models.ManyToManyField(
        StudentProfile,
        blank=True,
        related_name='students'
    )
    teachers = models.ManyToManyField(
        TeacherProfile,
        blank=True,
        related_name='teachers'
    )
    name = models.CharField(max_length=30, blank=False)


class TeacherProfile(models.Model):
    user = models.OneToOneField('CoursesUser', on_delete=models.CASCADE)


class StudentProfile(models.Model):
    user = models.OneToOneField('CoursesUser', on_delete=models.CASCADE)

当我尝试通过 POST 正文请求创建新课程时:

{
  "name": "Course",
  "students": [],
  "teachers": []
}

我想将 request.user 添加到教师归档 这是我对 Course

的看法
class CourseList(generics.ListAPIView):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer

    def post(self, request, format=None):
        serializer = CourseSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(creator=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Course 模型的序列化程序:

class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = ['id', 'name', 'students', 'teachers']

    def create(self, validated_data):
        creator_profile_id = TeacherProfile.objects.filter(
            user__id=validated_data['creator'].id
        )[0].id
        validated_data['teachers'].append(creator_profile_id)

        return Course(**validated_data)

但是有

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

我不明白如何在我的案例中使用 ```set()``

正确的做法是保存新模型,然后添加 ManyToMany 字段。 在 CourseSerializer.create():

def create(self, validated_data):
    creator_profile_id = TeacherProfile.objects.filter(
            user__id=validated_data['creator'].id
        )[0].id
    name = validated_data['name']
    course = Course(name=name)
    course.save()
    course.teachers.add(creator_profile_id)

    return course