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



我有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)

但是有

禁止直接分配给多对多集合的前端。请改用students.set((。

我不知道如何在中使用``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

相关内容

  • 没有找到相关文章

最新更新