I am using viewsets like this:
class UserViewSet(viewsets.ModelViewSet):
"""Viewset for model User."""
queryset = User.objects.all()
serializer_class = UserSerializer
and my serializer has following fields:
fields = ('id', 'url', 'username', 'first_name', 'middle_name', 'last_name', 'role',
'get_role_display', 'is_authenticated', 'is_staff', 'is_superuser', )
When I access the api to list all users with this url /api/user/
, it returns this json_data:
[
{
"id": 1,
"url": "http://127.0.0.1:8000/api/user/1/",
"username": "admin",
"first_name": "",
"middle_name": null,
"last_name": "",
"role": "A",
"get_role_display": "Admin",
"is_authenticated": true,
"is_staff": true,
"is_superuser": true
},
{
"id": 2,
"url": "http://127.0.0.1:8000/api/user/2/",
"username": "7004104463",
"first_name": "Vaibhav",
"middle_name": "Bold",
"last_name": "Vishal",
"role": "S",
"get_role_display": "Student",
"is_authenticated": true,
"is_staff": false,
"is_superuser": false
}
]
But what I am trying to do is returns only a few fields on list, say only 'id', 'username', 'url',
but on requests where a single object is requested like this /api/user/1/
I want to return all fields. I want to avoid using two different rest_framework views. I want a single viewset and serializer to achieve this. Is there any way to make it happen?
I am using React on frontend and I want to avoid fetching unnecessary data.