在 DRF 中过滤响应的特定数据
Filtering the specific data for response in DRF
我有以下响应数据
[
{
"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
]
}]
但是我想从响应数据中删除id = 10的字典,我该怎么做?
我有以下几行代码..
class GetUserGroupList(APIView):
def post(self, request, *args, **kwargs):
groups = Group.objects.all()
serializer = GroupSerializer(groups, many=True)
return Response(serializer.data)
在serializers.py
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('id', 'name', 'permissions',)
任何帮助将不胜感激!!
不确定你提到的 seializers.py 内容,但我写了这篇文章而不是完成工作:
response = [i for i in response if i['id'] != 10]
基本上,它遍历列表 response
,创建一个也称为 response
的新列表,除了新列表不包含任何 id
为 10 的字典
如果您执行以下操作会发生什么:
groups = Group.objects.exclude(id=10)
如果您想 include/exclude 响应中的某些项目,您可以过滤查询集以实现该目的。我建议您使用如下通用 API 视图:
from rest_framework import generics
class UserGroupListView(generics.ListAPIView):
serializer_class = GroupSerializer
queryset = Group.objects.exclude(permissions=10)
其实我有更早的解决方案如下,但是,还有其他更好的答案方式
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)
我有以下响应数据
[
{
"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
]
}]
但是我想从响应数据中删除id = 10的字典,我该怎么做?
我有以下几行代码..
class GetUserGroupList(APIView):
def post(self, request, *args, **kwargs):
groups = Group.objects.all()
serializer = GroupSerializer(groups, many=True)
return Response(serializer.data)
在serializers.py
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('id', 'name', 'permissions',)
任何帮助将不胜感激!!
不确定你提到的 seializers.py 内容,但我写了这篇文章而不是完成工作:
response = [i for i in response if i['id'] != 10]
基本上,它遍历列表 response
,创建一个也称为 response
的新列表,除了新列表不包含任何 id
为 10 的字典
如果您执行以下操作会发生什么:
groups = Group.objects.exclude(id=10)
如果您想 include/exclude 响应中的某些项目,您可以过滤查询集以实现该目的。我建议您使用如下通用 API 视图:
from rest_framework import generics
class UserGroupListView(generics.ListAPIView):
serializer_class = GroupSerializer
queryset = Group.objects.exclude(permissions=10)
其实我有更早的解决方案如下,但是,还有其他更好的答案方式
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)