Django Rest Framework:动态返回字段子集 [英] Django Rest Framework: Dynamically return subset of fields

查看:37
本文介绍了Django Rest Framework:动态返回字段子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

如博客文章中推荐的那样最佳实践设计一个实用的 RESTful API,我想向基于 Django Rest 框架的 API 添加一个 fields 查询参数,它使用户能够为每个资源只选择字段的子集.

示例

序列化器:

class IdentitySerializer(serializers.HyperlinkedModelSerializer):元类:模型 = 模型.身份字段 = ('id', 'url', 'type', 'data')

常规查询将返回所有字段.

GET/identities/

<预><代码>[{id":1,"url": "http://localhost:8000/api/identities/1/",类型":5,数据":John Doe"},...]

带有 fields 参数的查询应该只返回字段的子集:

GET/identities/?fields=id,data

<预><代码>[{id":1,数据":John Doe"},...]

具有无效字段的查询应忽略无效字段或引发客户端错误.

目标

这是否可以开箱即用?如果没有,实现这一点的最简单方法是什么?是否有第三方软件包可以做到这一点?

解决方案

您可以覆盖序列化器 __init__ 方法并根据查询参数动态设置 fields 属性.您可以在整个上下文中访问传递给序列化程序的 request 对象.

这是 Django Rest Framework 文档示例的复制和粘贴 关于此事:

<块引用>

from rest_framework 导入序列化程序类 DynamicFieldsModelSerializer(serializers.ModelSerializer):"""一个 ModelSerializer 需要一个额外的字段"参数控制应显示哪些字段."""def __init__(self, *args, **kwargs):# 正常实例化超类super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)fields = self.context['request'].query_params.get('fields')如果字段:fields = fields.split(',')# 删除任何未在 `fields` 参数中指定的字段.允许 = 设置(字段)现有 = 设置(self.fields.keys())对于现有的 field_name - 允许:self.fields.pop(field_name)类 UserSerializer(DynamicFieldsModelSerializer,serializers.HyperlinkedModelSerializer):元类:模型 = 用户字段=('网址','用户名','电子邮件')

Problem

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.

Example

Serializer:

class IdentitySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Identity
        fields = ('id', 'url', 'type', 'data')

A regular query would return all fields.

GET /identities/

[
  {
    "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.

Goal

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?

解决方案

You can override the serializer __init__ method and set the fields attribute dynamically, based on the query params. You can access the request object throughout the context, passed to the serializer.

Here is a copy&paste from Django Rest Framework documentation example on the matter:

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 Framework:动态返回字段子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆