Django Rest框架:动态返回字段子集 [英] Django Rest Framework: Dynamically return subset of fields
问题描述
如博客设计实用的RESTful API的最佳做法,我想将一个字段
查询参数添加到基于Django Rest框架的API这使得用户只能选择每个资源的字段子集。
As recommended in the blogpost Best Practices for Designing a Pragmatic RESTful API, I would like to add a fields
query parameter to a Django Rest Framework based API which enables the user to select only a subset of fields per resource.
序列化器:
class IdentitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Identity
fields = ('id', 'url', 'type', 'data')
将返回所有字段。
GET / identity /
[
{
"id": 1,
"url": "http://localhost:8000/api/identities/1/",
"type": 5,
"data": "John Doe"
},
...
]
使用字段
参数的查询只能返回字段的一个子集:
A query with the fields
parameter should only return a subset of the fields:
GET / identities /?fields = id,data
[
{
"id": 1,
"data": "John Doe"
},
...
]
无效字段的查询应忽略无效字段或引发客户端错误。
A query with invalid fields should either ignore the invalid fields or throw a client error.
这是否可以开箱即用?如果没有,最简单的实现方式是什么?有没有第三方软件包已经这样做了?
Is this possible out of the box somehow? If not, what's the simplest way to implement this? Is there a 3rd party package around that does this already?
推荐答案
您可以覆盖串行器 __ init __
方法,并根据查询参数设置字段
属性动态。您可以访问请求
对象的上下文,传递给序列化程序。
You can override the serializer __init__
method and set the fields
attribute dynamicaly, based on the query params. You can access the request
object trouth the context, passed to the serializer.
这里我创建了一个可重用的mixin,修改动态字段
Here I created a reusable mixin, that does the dynamic fields
modification.
from rest_framework import serializers
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""
def __init__(self, *args, **kwargs):
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
fields = self.context['request'].QUERY_PARAMS.get('fields')
if fields:
fields = fields.split(',')
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields.keys())
for field_name in existing - allowed:
self.fields.pop(field_name)
class UserSerializer(DynamicFieldsModelSerializer, serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email')
这篇关于Django Rest框架:动态返回字段子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!