Django Rest Framework: Dynamically return subset of fields

后端 未结 8 671
南笙
南笙 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 19:05

    You could try Dynamic REST, which has support for dynamic fields (inclusion, exclusion), embedded / sideloaded objects, filtering, ordering, pagination, and more.

    0 讨论(0)
  • 2020-11-28 19:11

    This functionality is available from a 3rd-party package.

    pip install djangorestframework-queryfields
    

    Declare your serializer like this:

    from rest_framework.serializers import ModelSerializer
    from drf_queryfields import QueryFieldsMixin
    
    class MyModelSerializer(QueryFieldsMixin, ModelSerializer):
        ...
    

    Then the fields can now be specified (client-side) by using query arguments:

    GET /identities/?fields=id,data
    

    Exclusion filtering is also possible, e.g. to return every field except id:

    GET /identities/?fields!=id
    

    disclaimer: I'm the author/maintainer.

    0 讨论(0)
提交回复
热议问题