我想向fields基于Django Rest Framework的API 添加查询参数,该参数使用户只能为每个资源选择字段的子集。
例 序列化器:
class IdentitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Identity fields = ('id', 'url', 'type', 'data')
常规查询将返回所有字段。
GET /identities/
[ { "id": 1, "url": "http://localhost:8000/api/identities/1/", "type": 5, "data": "John Doe" }, ... ]
具有fields参数的查询应仅返回字段的子集:
fields
GET /identities/?fields=id,data
[ { "id": 1, "data": "John Doe" }, ... ]
具有无效字段的查询应忽略无效字段或引发客户端错误。
目标 这是否可能开箱即用?如果没有,最简单的实现方法是什么?周围是否有第三方包装?
你可以覆盖序列化__init__方法,并fields根据查询参数动态设置属性。你可以在request整个上下文中访问对象,并将其传递给序列化程序。
__init__
request
这是此问题的Django Rest Framework文档示例的复制和粘贴:
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')