Nested field serializer - Data missing

前端 未结 1 920
名媛妹妹
名媛妹妹 2021-02-20 11:55

Related to this Topic


Hi, I cannot follow the answer at the attached topic, because an ID is missing after serializat

相关标签:
1条回答
  • 2021-02-20 12:39

    Any AutoFields on your model (which is what the automatically generated id key is) are set to read-only by default when Django REST Framework is creating fields in the background. You can confirm this by doing

    repr(CarSerializer())
    

    and seeing the field generated with read_only=True set. You can override this with the extra_kwargs Meta option which will allow you to override it and set read_only=False.

    class OwnerSerializer(serializers.ModelSerializer):
    
        class Meta:
            model =  Owner
            fields = ('id', 'name')
            extra_kwargs = {
                "id": {
                    "read_only": False,
                    "required": False,
                },
            }
    

    This will include the id field in the validated_data when you need it.

    0 讨论(0)
提交回复
热议问题