[英]How to return empty queryset from serializer.data Django Rest Framework
view.py视图.py
class User_ListView(APIView):
permission_classes = [DjangoCustomModelPermissions]
queryset = User.objects.none()
def get(self, request):
param1 = request.query_params.get('param1',None)
param2 = request.query_params.get('param2',None)
try:
db_data = User.objects.get(param1 = param1, param2=param2)
serializer = User_Serializer(db_data)
return Response(serializer.data)
except Closing_Stock_List_Trans.DoesNotExist:
db_data = User.objects.none()
serializer = User_Serializer(db_data)
return Response(serializer.data)
serializer.py序列化程序.py
class User_Serializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
I want the serializer to return an empty response when no User DoesNotExist in the User Model, however I get the following error.我希望序列化程序在用户 Model 中没有用户 DoesNotExist 时返回空响应,但是我收到以下错误。 How can i achieve this?我怎样才能做到这一点?
AttributeError: Got AttributeError when attempting to get a value for field `param1` on serializer `User_Serializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'param1'.
You are trying to serialize a queryset, so you need to add many=True
to the serialization.您正在尝试序列化查询集,因此您需要将many=True
添加到序列化中。
....
except Closing_Stock_List_Trans.DoesNotExist:
db_data = User.objects.none()
serializer = User_Serializer(db_data, many=True)
return Response(serializer.data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.