Django Rest Framework,外键字段的默认序列化程序

时间:2016-10-15 14:35:16

标签: django django-rest-framework

假设用户将地址作为外键

典型的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,
   }
}   

1 个答案:

答案 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替换为MyPrimaryKeyRelatedFieldserializers.ModelSerializerMyModelSerializer