drf-flex-fields

1.0.2 · active · verified Thu Apr 16

drf-flex-fields (DRF-FF) is a Python package for Django REST Framework that provides flexible, dynamic fields and nested resources for serializers. It allows clients to control which fields are included or excluded, and to dynamically expand related models via URL parameters like `?fields=id,name` or `?expand=organization.owner.roles`. The library focuses on simplicity with minimal entanglement with DRF's core classes. It is actively maintained with regular updates, including bug fixes and new features, as seen in the recent 1.0.x releases.

Common errors

Warnings

Install

Imports

Quickstart

To use `drf-flex-fields`, inherit your serializers from `FlexFieldsModelSerializer` and define `expandable_fields` in the `Meta` class. For viewsets, inherit from `FlexFieldsMixin` to enable query parameter processing. This allows dynamic field selection via `?fields=` and nested resource expansion via `?expand=` URL parameters. Remember to configure `permit_list_expands` on your viewset if you want to allow expansions on list endpoints, not just detail views.

import os
from django.db import models
from rest_framework import serializers, viewsets
from rest_flex_fields import FlexFieldsModelSerializer
from rest_flex_fields.views import FlexFieldsMixin

# Minimal Django setup for demonstration
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

# Define a simple Django model (e.g., in models.py)
class Country(models.Model):
    name = models.CharField(max_length=100)
    population = models.IntegerField()

    def __str__(self):
        return self.name

class State(models.Model):
    name = models.CharField(max_length=100)
    country = models.ForeignKey(Country, related_name='states', on_delete=models.CASCADE)

    def __str__(self):
        return self.name

# Define FlexFields serializers
class StateSerializer(FlexFieldsModelSerializer):
    class Meta:
        model = State
        fields = ('id', 'name')

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

# Define a ViewSet using FlexFieldsMixin
class CountryViewSet(FlexFieldsMixin, viewsets.ModelViewSet):
    queryset = Country.objects.all()
    serializer_class = CountrySerializer
    # Allow 'states' to be expanded on list views (GET /countries/)
    permit_list_expands = ['states']

# Example usage (conceptual, in a Django/DRF app context):
# GET /countries/1/?expand=states
# GET /countries/?fields=id,name

view raw JSON →