小编Nor*_*054的帖子

在REST-ful api中序列化外键字段的最佳做法是什么

我想用REST-ful api编写一个Django应用程序.Django REST框架提供了三个内置的模型序列化器:ModelSerializer,它序列化为类似的东西

{
    'normal_field': 'value',
    'foreign_key_field': 42
}
Run Code Online (Sandbox Code Playgroud)

和HyperlinkedModelSerializer串行化为这样的东西

{
    'normal_field': 'value',
    'foreign_key_field': 'http://domain/api/myothermodel/11'
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,是否有另一种好的方法来序列化数据,以便客户端直接知道哪些字段必须解析,哪些字段不能解析.

示例:接收此内容的客户端

{ 
    'foo': 'http://domain/api/myothermodel/11',
    'bar': 'http://otherdomain/api/myothermodel/12'
}
Run Code Online (Sandbox Code Playgroud)

不知道foo或bar是否应该是可解析的外键字段而不是普通的url.就像是:

{ 
    'foo': 'http://domain/api/myothermodel/11', # Here the client might know that this is only a plain url.
    'bar': {
            '_foreignkey': true,  # Tells the client that this field should behave as a foreign key which has to be resolved first
            'url': 'http://otherdomain/api/myothermodel/12'
        }
}
Run Code Online (Sandbox Code Playgroud)

有没有标准或最佳做法?或者最好的做法是客户端不是从JSON知道这个,而是从服务器上获得或从服务器获取的其他代码?

更新:可选您可以添加哪种方式是一些众所周知的客户端库,如AngularJS的最佳实践.

django rest serialization json django-rest-framework

6
推荐指数
1
解决办法
2662
查看次数