1
When I try to save a new student informs the error
NOT NULL Constraint failed: student_student.teacher_id
Can someone help me?
class Teacher(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Student(models.Model):
teacher = models.ForeignKey(Teacher, related_name='teacher', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
class TeacherSerializer(ModelSerializer):
class Meta:
model = Teacher
fields = ['name']
class StudentSerializer(ModelSerializer):
teacher = TeacherSerializer()
class Meta:
model = Student
fields = ['id','name','teacher']
def create(self, validated_data):
teacher_data = validated_data.pop('teacher')
student = Student.objects.create(**validated_data)
student.teacher=teacher_data
student.save()
return student
class TeacherViewSet(ModelViewSet):
queryset = Teacher.objects.all()
serializer_class = TeacherSerializer
class StudentViewSet(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
{
"id": 1,
"name": "Pablo",
"teacher": {
"name": "Pedro"
}
}