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 | from rest_framework import serializers |
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: