This package is no longer actively maintianed
See: https://github.com/dbrgn/drf-dynamic-fields or https://github.com/dbrgn/drf-dynamic-fields
pip install drf-restricted-fields
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
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"
},
...
],
}
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]"
},
...
],
}
- Free software: MIT license
- Documentation: https://drf-restricted-fields.readthedocs.io.
If you feel generous and want to show some extra appreciation