假设用户将地址作为外键
典型的PrimaryKeyRelatedField将通过id:
表示外键{
id: 3,
first_name: eugene,
last_name: kim,
address: 9 # here 9 is address's id
}
我想更改外键字段的默认表示,如下例所示。 (希望没有我为每个外键字段定义序列化器)
{
id: 3,
first_name: eugene,
last_name: kim,
address: {
id: 9 # difference here,
}
}
答案 0 :(得分:1)
试试这个
class MyPrimaryKeyRelatedField(PrimaryKeyRelatedField)
def to_representation(self, value):
if self.pk_field is not None:
return self.pk_field.to_representation(value.pk)
return {"id": value.pk}
更新
class MyModelSerializer(serializers.ModelSerializer)
serializer_related_field = MyPrimaryKeyRelatedField
然后将PrimaryKeyRelatedField
替换为MyPrimaryKeyRelatedField
和
serializers.ModelSerializer
至MyModelSerializer