Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
D

drf-flex-fields

> 后端框架
Open source

Dynamically set fields and expand nested resources in Django REST Framework serializers.

768 stars0 likes1 views
WebsiteGitHub

About

Dynamically set fields and expand nested resources in Django REST Framework serializers.

Django REST - FlexFields

Flexible, dynamic fields and nested models for Django REST Framework serializers.

Overview

FlexFields (DRF-FF) for Django REST Framework is a package designed to provide a common baseline of functionality for dynamically setting fields and nested models within DRF serializers. This package is designed for simplicity, with minimal magic and entanglement with DRF's foundational classes.

Key benefits:

  • Easily set up fields that be expanded to their fully serialized counterparts via query parameters (users/?expand=organization,friends)
  • Select a subset of fields by either:
    • specifying which ones should be included (users/?fields=id,first_name)
    • specifying which ones should be excluded (users/?omit=id,first_name)
  • Use dot notation to dynamically modify fields at arbitrary depths (users/?expand=organization.owner.roles)
  • Flexible API - options can also be passed directly to a serializer: UserSerializer(obj, expand=['organization'])

Quick Start

…
GET /people/142/
json
{
  "id": 142,
  "name": "Jim Halpert",
  "country": 1
}
GET /people/142/?expand=country.states
json
{
  "id": 142,
  "name": "Jim Halpert",
  "country": {
    "id": 1,
    "name": "United States",
    "states": [
      {
        "id": 23,
        "name": "Ohio"
      },
      {
        "id": 2,
        "name": "Pennsylvania"
      }
    ]
  }
}

Table of Contents:

  • Django REST - FlexFields
  • Overview
  • Quick Start
  • Table of Contents:
  • Setup
  • Usage
    • Dynamic Field Expansion
    • Deferred Fields
    • Deep, Nested Expansion
    • Field Expansion on "List" Views
    • Expanding a "Many" Relationship
    • Dynamically Setting Fields (Sparse Fields)
    • Reference serializer as a string (lazy evaluation)
    • Increased re-usability of serializers
  • Serializer Options
  • Advanced
    • Customization
    • Serializer Introspection
    • Use Wildcards to Match Multiple Fields
    • Combining Sparse Fields and Field Expansion
    • Utility Functions
      • rest_flex_fields.is_expanded(request, field: str)
      • rest_flex_fields.is_included(request, field: str)
    • Query optimization (experimental)
  • Changelog
  • Testing
  • License

Setup

First install:

bash
pip install drf-flex-fields

Then have your serializers subclass FlexFieldsModelSerializer:

python
from rest_flex_fields import FlexFieldsModelSerializer

class StateSerializer(FlexFieldsModelSerializer):
    class Meta:
        model = Country
        fields = ('id', 'name')

class CountrySerializer(FlexFieldsModelSerializer):
    class Meta:
        model = Country
        fields = ('id', 'name', 'population', 'states')
        expandable_fields = {
          'states': (StateSerializer, {'many': True})
        }

Alternatively, you can add the FlexFieldsSerializerMixin mixin to a model serializer.

Usage

Dynamic Field Expansion

To define expandable fields, add an expandable_fields dictionary to your serializer's Meta class. Key the dictionary with the name of the field that you want to dynamically expand, and set its value to either the expanded serializer or a tuple where the first element is the serializer and the second is a dictionary of options that will be used to instantiate the serializer.

python
class CountrySerializer(FlexFieldsModelSerializer):
    class Meta:
        model = Country
        fields = ['name', 'population']

class PersonSerializer(FlexFieldsModelSerializer):
    country = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Person
        fields = ['id', 'name', 'country', 'occupation']

        expandable_fields = {
            'country': CountrySerializer
        }

If the default serialized response is the following:

json
{
  "id": 13322,
  "name": "John Doe",
  "country": 12,
  "occupation": "Programmer"
}

When you do a GET /person/13322?expand=country, the response will change to:

json
{
  "id": 13322,
  "name": "John Doe",
  "country": {
    "name": "United States",
    "population": 330000000
  },
  "occupation": "Programmer"
}

Deferred Fields

Alternatively, you could treat country as a "deferred" field by not defining it among the default fields. To make a field deferred, only define it within the serializer's expandable_fields.

Deep, Nested Expansion

Let's say you add StateSerializer as a serializer nested inside the country serializer above:

…

Your default serialized response might be the following for person and country, respectively:

json
{
  "id" : 13322,
  "name" : "John Doe",
  "country" : 12,
  "occupation" : "Programmer",
}

{
  "id" : 12,
  "name" : "United States",
  "states" : "http://www.api.com/countries/12/states"
}

But if you do a GET /person/13322?expand=country.states, it would be:

json
{
  "id": 13322,
  "name": "John Doe",
  "occupation": "Programmer",
  "country": {
    "id": 12,
    "name": "United States",
    "states": [
      {
        "name": "Ohio",
        "population": 11000000
      }
    ]
  }
}

Please be kind to your database, as this could incur many additional queries. Though, you can mitigate this impact through judicious use of prefetch_related and select_related when defining the queryset for your viewset.

Field Expansion on "List" Views

If you request many objects, expanding fields could lead to many additional database queries. Subclass FlexFieldsModelViewSet if you want to prevent expanding fields by default when calling a ViewSet's list method. Place those fields that you would like to expand in a permit_list_expands property on the ViewSet:

python
from rest_flex_fields import is_expanded

class PersonViewSet(FlexFieldsModelViewSet):
    permit_list_expands = ['employer']
    serializer_class = PersonSerializer

    def get_queryset(self):
        queryset = models.Person.objects.all()
        if is_expanded(self.request, 'employer'):
            queryset = queryset.select_related('employer')
        return queryset

Notice how this example is using the is_expanded utility method as well as select_related and prefetch_related to efficiently query the database if the field is expanded.

Expanding a "Many" Relationship

Set many to True in the serializer options to make sure "to many" fields are expanded correctly.

python
class StateSerializer(FlexFieldsModelSerializer):
    class Meta:
        model = State
        fields = ['name', 'population']

class CountrySerializer(FlexFieldsModelSerializer):
    class Meta:
        model = Country
        fields = ['name', 'population']

        expandable_fields = {
            'states': (StateSerializer, {'many': True})
        }

A request to GET /countries?expand=states will return:

python
{
    "id" : 12,
    "name" : "United States",
    "states" : [
      {
        "name" : "Alabama",
        "population": 11000000
      },
      //... more states ... //
      {
        "name" : "Ohio",
        "population": 11000000
      }
    ]
}

Dynamically Setting Fields (Sparse Fields)

You can use either the fields or omit keywords to declare only the fields you want to include or to specify fields that should be excluded.

Consider this as a default serialized response:

json
{
  "id": 13322,
  "name": "John Doe",
  "country": {
    "name": "United States",
    "population": 330000000
  },
  "occupation": "Programmer",
  "hobbies": ["rock climbing", "sipping coffee"]
}

To whittle down the fields via URL parameters, simply add ?fields=id,name,country to your requests to get back:

json
{
  "id": 13322,
  "name": "John Doe",
  "country": {
    "name": "United States",
    "population": 330000000
  }
}

Or, for more specificity, you can use dot-notation, ?fields=id,name,country.name:

json
{
  "id": 13322,
  "name": "John Doe",
  "country": {
    "name": "United States"
  }
}

Or, if you want to leave out the nested country object, do ?omit=country:

json
{
  "id": 13322,
  "name": "John Doe",
  "occupation": "Programmer",
  "hobbies": ["rock climbing", "sipping coffee"]
}

Reference serializer as a string (lazy evaluation)

To avoid circular import problems, it's possible to lazily evaluate a string reference to you serializer class using this syntax:

python
expandable_fields = {
    'record_set': ('.RelatedSerializer', {'many': True})
}

Note: Prior to version 0.9.0, it was assumed your serializer classes would be in a module with the following path: .serializers.

This import style will still work, but you can also now specify fully-qualified import paths to any locations.

Increased re-usability of serializers

The omit and fields options can be passed directly to serializers. Rather than defining a separate, slimmer version of a regular serializer, you can re-use the same serializer and declare which fields you want.

python
from rest_flex_fields import FlexFieldsModelSerializer

class CountrySerializer(FlexFieldsModelSerializer):
    class Meta:
        model = Country
        fields = ['id', 'name', 'population', 'capital', 'square_miles']

class PersonSerializer(FlexFieldsModelSerializer):
    country = CountrySerializer(fields=['id', 'name'])

    class Meta:
        model = Person
        fields = ['id', 'name', 'country']

serializer = PersonSerializer(person)
print(serializer.data)

>>>{
  "id": 13322,
  "name": "John Doe",
  "country": {
    "id": 1,
    "name": "United States",
  }
}

Serializer Options

Dynamic field options can be passed in the following ways:

  • from the request's query parameters; separate multiple values with a commma
  • as keyword arguments directly to the serializer class when its constructed
  • from a dictionary placed as the second element in a tuple when defining expandable_fields

Approach #1

GET /people?expand=friends.hobbies,employer&omit=age

Approach #2

python
serializer = PersonSerializer(
  person,
  expand=["friends.hobbies", "employer"],
  omit="friends.age"
)

Approach #3

python

class PersonSerializer(FlexFieldsModelSerializer):
  // Your field definitions

  class Meta:
    model = Person
    fields = ["age", "hobbies", "name"]
    expandable_fields = {
      'friends': (
        'serializer.FriendSerializer',
        {'many': True, "expand": ["hobbies"], "omit": ["age"]}
      )
    }
Option Description
expand Fields to expand; must be configured in the serializer's expandable_fields
fields Fields that should be included; all others will be excluded
omit Fields that should be excluded; all others will be included

Advanced

Customization

Parameter names and wildcard values can be configured within a Django setting, named REST_FLEX_FIELDS.

| Option |

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Pythondjangodjango-rest-frameworkfield-expansion

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架