Skip to content
This repository has been archived by the owner on Jan 3, 2022. It is now read-only.

tj-django/drf-restricted-fields

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This package is no longer actively maintianed

See: https://github.com/dbrgn/drf-dynamic-fields or https://github.com/dbrgn/drf-dynamic-fields

drf-restricted-fields

Documentation Status Updates Total alerts Language grade: Python pre-commit.ci status

Installation

pip install drf-restricted-fields

Usage

serializer.py

from rest_framework import serializers
from restricted_fields import RestrictedFieldsSerializerMixin

User = get_user_model()


class UserSerializer(RestrictedFieldsSerializerMixin, serializers.ModelSerializer)

    class Meta:
        model = User
        fields = (
            'id',
            'name',
            'email',
            'is_staff',
        )

api/views.py

from rest_framework import viewsets

from my_app.api.serializer import UserSerializer

User = get_user_model()


class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    API endpoint to retrieve all users
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

Features

Restrict fields returned by DRF serializers using the only query parameter

GET http://127.0.0.1:8000/api/users/?only=id&only=name

Serialize only the id and name fields.

{
    "count": 198,
    "next": "http://127.0.0.1:8000/api/users/?only=id&only=name&page=2",
    "previous": null,
    "results":[
        {
            "id": 1,
            "name": "Test user"
        },
        ...
    ],
}

Defer fields returned by DRF serializers using the defer query parameter

GET http://127.0.0.1:8000/api/users/?defer=name&defer=is_staff

Serialize all except the name and is_staff fields.

{
    "count": 198,
    "next": "http://127.0.0.1:8000/api/users/?defer=name&defer=age&page=2",
    "previous": null,
    "results":[
        {
            "id": 1,
            "email": "[email protected]"
        },
        ...
    ],
}

If you feel generous and want to show some extra appreciation

Buy me a coffee