This package provides a mixin that allows the user to dynamically select only a subset of fields per resource.
pip install drf-dynamic-fields
Example serializer:
python
- class IdentitySerializer(DynamicFieldsMixin, serializers.HyperlinkedModelSerializer):
- class Meta:
model = models.Identity fields = ('id', 'url', 'type', 'data')
A regular request returns all fields:
GET /identities
A query with the fields parameter on the other hand returns only a subset of the fields:
GET /identities/?fields=id,data
And a query with the omit parameter excludes specified fields.
GET /identities/?omit=data
You can use both fields and omit in the same request!
GET /identities/?omit=data,fields=data,id
Though why you would want to do something like that is beyond this author.
It also works on single objects!
GET /identities/1/?fields=id,data
json
- {
"id": 1, "data": "John Doe"
}
When defining a serializer, use the DynamicFieldsMixin
:
python
from drf_dynamic_fields import DynamicFieldsMixin
- class IdentitySerializer(DynamicFieldsMixin, serializers.ModelSerializer):
- class Meta:
model = models.Identity fields = ('id', 'url', 'type', 'data')
The mixin needs access to the request
object. Some DRF classes like the ModelViewSet
set that by default, but if you handle serializers yourself, pass in the request through the context:
python
events = Event.objects.all() serializer = EventSerializer(events, many=True, context={'request': request})
This library is about filtering fields based on individual requests. It is deliberately kept simple and we do not plan to add new features. Feel free to contribute improvements, code simplifications and bugfixes though! (See also: #18)
If you need more advanced filtering features, maybe drf-flex-fields could be something for you.
To run tests, install Django and DRF and then run runtests.py
:
$ python runtests.py
- The implementation is based on this StackOverflow answer. Thanks
YAtOff
! - The GitHub users
X17
andrawbeans
provided improvements on my gist that were incorporated into this library. Thanks! - For other contributors, please see Github contributor stats.
MIT license, see LICENSE
file.