简体   繁体   中英

Django Rest Framework : Setting foreign key value in serializer

I have the following models:

     class School(models.Model):
         id = patch.BigAutoField(primary_key=True)
         name = models.CharField('Name', max_length=100)
         address = models.CharField('Address', max_length=500, blank=True, null=True)

     class Child(BaseModel):
         id = patch.BigAutoField(primary_key=True)
         name = models.CharField('Name', max_length=100, blank=True, null=True)
         school = models.ForeignKey('User', blank=True, null=True, db_constraint=False, db_index=True, on_delete=models.CASCADE, default=None)

I have the following serializers :

    class SchoolSerializer(serializers.Serializer):
        id = serializers.IntegerField(read_only=True)
        name = serializers.CharField(required=True, max_length=100)
        address = serializers.CharField(required=False, max_length=400)

        def create(self, validated_data):
            return School.objects.create(**validated_data)

        def update(self, instance, validated_data):
            instance.name = validated_data.get('name', instance.name)
            instance.address = validated_data.get('address', instance.address)
            instance.save()
            return instance

        class Meta:
            model = School
            fields = ('id', 'name', 'address')

    class ChildSerializer(serializers.Serializer):
        id = serializers.IntegerField(read_only=True)
        name = serializers.CharField(required=False, max_length=100, allow_blank=False)
        school = SchoolSerializer()

        def create(self, validated_data):
            return Child.objects.create(**validated_data)

        def update(self, instance, validated_data):
            instance.name = validated_data.get('name', instance.name)
            instance.school = validated_data.get('school', instance.school)
            instance.save()
            return instance

Now the problem that I am facing is that when I saving any value in my child table using serializer then the value of school is showing null in my database but in my request object I am getting value for school_id .

Since this school = SchoolSerializer() school would be a fully serialized object, not scalar value.

Take a look at this example it should help: Writable nested serializer with existing objects using Django Rest Framework 3.2.2

You got to convert serialized object school manually into scalar valued school PK to fill school_id FK field. Or just remove school = SchoolSerializer() , then ChildSerializer will start serializing this field as scalar-valued (but still FK) and thus will make it simply writable directly to the school_id field. The rest of the code should work well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM