Dynamically return subset of Django REST Framework serializer fields
Project description
This package provides a mixin that allows the user to dynamically select only a subset of fields per resource.
What It Does
Example serializer:
class IdentitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Identity fields = ('id', 'url', 'type', 'data')
A regular request returns all fields:
GET /identities
[ { "id": 1, "url": "http://localhost:8000/api/identities/1/", "type": 5, "data": "John Doe" }, ... ]
A query with the fields parameter on the other hand returns only a subset of the fields:
GET /identities/?fields=id,data
[ { "id": 1, "data": "John Doe" }, ... ]
It also works on single objects!
GET /identities/1/?fields=id,data
{ "id": 1, "data": "John Doe" }
Usage
When defining a serializer, use the 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:
events = Event.objects.all() serializer = EventSerializer(events, many=True, context={'request': request})
Credits
License
MIT license, see LICENSE file.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file drf_dynamic_fields-0.1.0.tar.gz
.
File metadata
- Download URL: drf_dynamic_fields-0.1.0.tar.gz
- Upload date:
- Size: 2.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 05487348f03d533dbaf9b44094c2fbec45fd85c7da5c00a49513716407ad423e |
|
MD5 | 7924080697ddf436a91795d1bc69fed1 |
|
BLAKE2b-256 | 172ffdd029d0351d76f63a0c321771c267801387d4b400d8d0b926c1f8602b61 |
File details
Details for the file drf_dynamic_fields-0.1.0-py2.py3-none-any.whl
.
File metadata
- Download URL: drf_dynamic_fields-0.1.0-py2.py3-none-any.whl
- Upload date:
- Size: 4.8 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | cd258d8e500d53ff53af70d866226dbeb29426929858e47ae89f06a575eb0041 |
|
MD5 | 3f0f8e157b9363539baea5fe642c73ad |
|
BLAKE2b-256 | 1f13a9562943f3dafa86556ef762a671c26750ed79afc0aa8eee8b77ab9601a8 |