Saving relationships using the Django Rest Framework

Asked

Viewed 48 times

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"
        }
    }

1 answer

0

Ola, First ,The problem may possibly be the database, do the shell commands again:

python manage.py makemigrations

and then and

python manage.py migrate

See if changes appeared.

Second, the other possible mistake is that you created a ForeignKey by default and she can’t stay Null, you have to confirm as Null=True, then:

teacher = models.ForeignKey(Teacher,null=True, blank=True, related_name='teacher', on_delete=models.CASCADE)

I hope you helped.

Reference link : https://stackoverflow.com/questions/42733221/django-db-utils-integrityerror-not-null-constraint-failed-products-product-ima/46497052#46497052

Browser other questions tagged

You are not signed in. Login or sign up in order to post.