A serializer that handles field configuration with multiple actions from ViewSets.
Project description
Action Serializer
Source: https://github.com/gregschmit/drf-action-serializer
PyPI: https://pypi.org/project/drf-action-serializer/
Action Serializer is a Django Rest Framework extension package that provides a Serializer that implements per-action field configuration for use in your drf-powered API.
The Problem: When building APIs, often you want different serializers for different actions, such as less fields on a list view vs a detail view. Normally you would have to build multiple Serializers to support this.
The Solution: This app provides the ModelActionSerializer which allows you to easily configure per-action fields.
How to Use
$ pip install drf-action-serializer
In your serializer, inherit from action_serializer.ModelActionSerializer.
In your serializer, you can add a action_fields dictionary to the Meta class and use fields, exclude, and extra_kwargs under the action key. The example in this project shows how to remder a smaller list of attributes for a list view compared to the detail view.
from django.contrib.auth.models import Group
from .serializers import ModelActionSerializer
class GroupActionSerializer(ModelActionSerializer):
"""
An example serializer for the Django ``Group`` model with details, and the
list view has less fields than the detail.
"""
class Meta:
model = Group
fields = ('id', 'name', 'permissions')
action_fields = {
'list': {
'fields': ('id', 'name'),
},
}
In your ViewSet, just set the serializer like normal:
from rest_framework.viewsets import ModelViewSet
class GroupViewSet(ModelViewSet):
"""
An example viewset for the Django ``Group`` model.
"""
serializer_class = GroupActionSerializer
queryset = Group.objects.all()
Tests
Since this package is essentially a relatively minor change to Django Rest Framework, I will be testing this by incorporating the code into that project.
This package should be considered a proof of concept. If you run this as a project (using python manage.py runserver), you will see that the API renders a Group model with different fields in the list vs detail actions.
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
Hashes for drf-action-serializer-0.1.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2e42395ff057cf816e1bef64a69322b7147273bb76f86bd01287fec026875fb0 |
|
MD5 | 4d3d8e7a884f309d220ce7cd63d33669 |
|
BLAKE2b-256 | 2c3c0116ca46792d7fbe962f4e4e247882438b839992cecdd5552902873952c9 |
Hashes for drf_action_serializer-0.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | e287750b1bef47166922f0f53801bf45ba189da88b0b48d7bcb33371827258e4 |
|
MD5 | 26deb7d4c6a5e242051a199390b5fa65 |
|
BLAKE2b-256 | 41b2a3294031e8ace13ef2d603ca4739725434b86481c78913104b7ccf048918 |