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-fieldsserializer.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 = UserSerializerGET http://127.0.0.1:8000/api/users/?only=id&only=nameSerialize 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_staffSerialize 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": "test@test.com"
},
...
],
}- Free software: MIT license
- Documentation: https://drf-restricted-fields.readthedocs.io.
If you feel generous and want to show some extra appreciation