【发布时间】:2022-01-13 13:46:59
【问题描述】:
我对 DRF 非常陌生,并且需要使用 DRF 的 REST API URL,这将允许 2 个或多个参数,但应该需要一个参数,即:需要句点并且实体可以为空白
http://127.0.0.1:8000/myapi/?entity=&period=FEB-21
我创建了如下 APIView:
class myAPI_Viw(APIView):
serializer_class = myAPI_Serializers
def get(self, request, format=None):
entity_param = self.request.query_params.get('entity')
period_param = self.request.query_params.get('period')
if (entity_param in (None, '') and period_param in (None, '')):
return Response({"status": "Error", "data": "Invalid parameter, period should have value"}, status=status.HTTP_400_BAD_REQUEST)
if (entity_param in (None, '') and period_param not in (None, '')):
rs = myAPI.objects.filter(period_name=period_param)
print(rs.query)
else:
rs = myAPI.objects.filter(entity=entity_param, period_name=period_param)
print(rs.query)
serializer = myAPI_Serializers(rs, many=True)
return Response({"status": "Success", "data": serializer.data}, status=status.HTTP_200_OK)
以上代码运行正常。 只是想知道:
- 任何更好的验证方法
- 视图和序列化程序级别的验证有什么区别
- 是否有任何方法可以将过滤器组合到一个调用中,以便 entity=entity_param 即使传入的值为空白也能正常工作
提前非常感谢, 防御
2.
【问题讨论】:
标签: django-rest-framework django-views