我有Course
、TeacherProfile
和StudentProfile
模型,它们具有以下关系:
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