Skip to content
A serializer for the Django Rest Framework that supports per-action serialization of fields.
Python
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
action_serializer
.gitignore
.pylintrc
.travis.yml
LICENSE
README.rst
manage.py
requirements.txt
setup.py

README.rst

Action Serializer

TravisCI PyPI Coveralls Code Style

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 serialization.

How to Use

$ pip install drf-action-serializer

In your serializer, inherit from action_serializer.ModelActionSerializer.

In your serializer, you can add an 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 render a smaller list of attributes for a list view compared to the detail view.

from django.contrib.auth.models import Group
from action_serializer import ModelActionSerializer


class GroupActionSerializer(ModelActionSerializer):
    """
    An example serializer for the Django ``Group`` model, where the ``list`` action
    causes less fields to be serialized than normal.
    """

    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

$ python manage.py test
You can’t perform that action at this time.