Django Rest Framework:在序列化程序中设置外键值

时间:2018-08-13 08:33:09

标签: python django django-rest-framework

我有以下型号:

     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)

我有以下序列化器:

    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

现在我面临的问题是,当我使用序列化程序将任何值保存在子表中时,school的值在数据库中显示为空,但是在我的请求对象中,我正在获得school_id的值。

1 个答案:

答案 0 :(得分:0)

因为这所school = SchoolSerializer()学校将是一个完全序列化的对象,而不是标量值。

看看这个例子,它应该可以帮助:Writable nested serializer with existing objects using Django Rest Framework 3.2.2

您必须将序列化对象school手动转换为标量值的学校PK,以填充school_id FK字段。或仅删除school = SchoolSerializer(),然后ChildSerializer将开始将此字段序列化为标量值(但仍为FK),从而使其直接可直接写入school_id字段。其余代码应该可以正常工作。