knktc's Notes

python, cloud, linux...

0%

Dynamic Fields in Django REST Framework

When I build data APIs, I like adding a fields query parameter so the client can choose exactly which fields to return. That reduces unnecessary network traffic. But when I started using Django REST Framework, I found that this feature was not included by default.

After searching around, I found a GitHub project called drf-dynamic-fields, and it solved the problem nicely.

Install

Project name: drf-dynamic-fields

Description: a mixin for DRF serializers that makes returned fields configurable dynamically.

GitHub:

https://github.com/dbrgn/drf-dynamic-fields

Installation is straightforward:

1
pip install drf-dynamic-fields

If you do not want to add a dependency, you can also copy the class directly from the project’s drf_dynamic_fields/__init__.py file into your own project.

Configure

To use it, just add DynamicFieldsMixin to your serializer.

Example:

1
2
3
4
5
6
7
8
9
from rest_framework import serializers
from drf_dynamic_fields import DynamicFieldsMixin
from .models import Book


class BookSerializer(DynamicFieldsMixin, serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'

That is all you need.

Usage

You can now use fields in the URL to specify which fields should be returned. For example, if you only want the book name and author:

1
GET https://knktc.com/book/?fields=name,author

This also works when querying a single object:

1
GET https://knktc.com/book/666/?fields=name,author

If you instead want to exclude a few fields, you can use omit. For example, if you want everything except the description:

1
GET https://knktc.com/book/?omit=description

Reference

The project author mentions on GitHub that the library is intentionally kept simple and is not expected to grow many more features. If you need something more powerful, take a look at:

https://github.com/rsinger86/drf-flex-fields

如果我的文字帮到了您,那么可不可以请我喝罐可乐?