Django Rest Framework: Dynamically return subset of fields

后端 未结 8 719
南笙
南笙 2020-11-28 18:16

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 R

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 18:59

    If you want something flexible like GraphQL, you can use django-restql. It supports nested data (both flat and iterable).

    Example

    from rest_framework import serializers
    from django.contrib.auth.models import User
    from django_restql.mixins import DynamicFieldsMixin
    
    class UserSerializer(DynamicFieldsMixin, serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ('id', 'username', 'email', 'groups')
    

    A regular request returns all fields.

    GET /users

        [
          {
            "id": 1,
            "username": "yezyilomo",
            "email": "yezileliilomo@hotmail.com",
            "groups": [1,2]
          },
          ...
        ]
    

    A request with the query parameter on the other hand returns only a subset of the fields:

    GET /users/?query={id, username}

        [
          {
            "id": 1,
            "username": "yezyilomo"
          },
          ...
        ]
    

    With django-restql you can access nested fields of any level. E.g

    GET /users/?query={id, username, date_joined{year}}

        [
          {
            "id": 1,
            "username": "yezyilomo",
            "date_joined": {
                "year": 2018
            }
          },
          ...
        ]
    

    For iterable nested fields, E.g groups on users.

    GET /users/?query={id, username, groups{id, name}}

        [
          {
            "id": 1,
            "username": "yezyilomo",
            "groups": [
                {
                    "id": 2,
                    "name": "Auth_User"
                }
            ]
          },
          ...
        ]
    

提交回复
热议问题