'Filtering the specific data for response in DRF
I have following response data
[
{
"id": 7,
"name": "Default Group",
"permissions": [
22,
24
]
},
{
"id": 10,
"name": "Another Group",
"permissions": [
1,
2,
22,
24
]
},
{
"id": 11,
"name": "New Group",
"permissions": [
10,
11,
12,
5,
6,
7,
8
]
}]
But I want to remove the dictionary whose id = 10 from the response data ,how can I do that ?
I have following lines of code..
class GetUserGroupList(APIView):
def post(self, request, *args, **kwargs):
groups = Group.objects.all()
serializer = GroupSerializer(groups, many=True)
return Response(serializer.data)
In serializers.py
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('id', 'name', 'permissions',)
Any help would be appreciated !!
Solution 1:[1]
If you want to include/exclude certain items from the response, you can filter queryset for achieving that. I recommend you to use generic API views like below:
from rest_framework import generics
class UserGroupListView(generics.ListAPIView):
serializer_class = GroupSerializer
queryset = Group.objects.exclude(permissions=10)
Solution 2:[2]
Not sure about the seializers.py stuff you mentioned but I wrote this one-liner than gets the job done:
response = [i for i in response if i['id'] != 10]
Basically, it iterates through the list response, creating a new list that is also called response, except the new list does not contain any dict with an id of 10
Solution 3:[3]
Actually I had earlier solution as below but ,there are other better ways in answers as well
groups = Group.objects.all()
serializer = GroupSerializer(groups, many=True)
data_is = list(serializer.data)
print(type(data_is))
for item in data_is[:]:
if item['id'] == 10:
data_is.remove(item)
print(data_is)
return Response(data_is)
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 | Elgin Cahangirov |
| Solution 2 | Andrew |
| Solution 3 | manoj adhikari |
