'DRF show different fields on 'list' and 'get_object' [duplicate]
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.
Solution 1:[1]
The only way that I know of is to overwrite the get_serializer_class
-Method and return a different Serializer
based on the current request.
class UserViewSet(viewsets.ModelViewSet):
....
def get_serializer_class(self):
if self.action == 'retrieve':
return UserDetailSerializerClass
return UserListSerializerClass
There is also a pypi package
Credits: https://stackoverflow.com/a/22755648/7774036 & https://stackoverflow.com/a/30670569/7774036
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yann |