Django DRF的GET方法验证

wztqucjr  于 2023-05-13  发布在  Go
关注(0)|答案(3)|浏览(123)

我认为DRF框架/ django有更好的方法来做到这一点。

class Providers(APIView):
    def get(self, request):
        from .doctor_search_helper import DoctorSearchHelper
        from .gmaps_helper import GMapsHelper

        localizacao = request.query_params.get("localizacao", None)
        especialidade = request.query_params.get("especialidade", None)
        plano = request.query_params.get("plano", None)
        tipo_estabelecimento = request.query_params.get("tipo_estabelecimento", None)
        distancia_maxima = request.query_params.get("distancia_maxima", None)

        if (not localizacao) or (localizacao == ""):
            return Response({"error": "localizacao is required"}, status=400)
        if (not especialidade) or (especialidade == ""):
            return Response({"error": "especialidade is required"}, status=400)
        if (not plano) or (plano == ""):
            return Response({"error": "plano is required"}, status=400)

        if (not plano) or (plano == ""):
            return Response({"error": "plano is required"}, status=400)

        if (not distancia_maxima) or (distancia_maxima == ""):
            return Response({"error": "distancia_maxima is required"}, status=400)

DRF是否有任何支持验证的库?

fwzugrvs

fwzugrvs1#

可以使用Django-Filter
示例代码:

from django_filters import rest_framework as filters
from myapp import Product
from rest_framework import generics

class ProductFilter(filters.FilterSet):
    localizacao= filters.CharField(field_name="localizacao", required=True)
    max_price = filters.NumberFilter(field_name="price", lookup_expr='lte', required=True)

    class Meta:
        model = Product
        fields = ['localizacao', 'max']

class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_class = ProductFilter
t5zmwmid

t5zmwmid2#

它确实有自己的Validators,当您试图验证一些可能与某些Model相关的通用数据时,可以与serializers一起使用。
但是,在您的示例中,您只是试图验证请求中是否存在某些查询字符串参数。而且,我相信正确的地方是在视图中,就像你正在做的那样。
也就是说,您的代码相当冗余。条件链接总是相同的,清理视图的一种可能方法是将要验证的信息收集到一个对象中,然后循环:

class Providers(APIView):
    def get(self, request):
        params = {        
            'localizacao': request.query_params.get("localizacao", None),
            'especialidade': request.query_params.get("especialidade", None),
            'plano': request.query_params.get("plano", None),
            'tipo_estabelecimento': request.query_params.get("tipo_estabelecimento", None),
            'distancia_maxima': request.query_params.get("distancia_maxima", None)
        }

        for key, value in params.items():
            if not value or value.strip() == '':
                error_message = f'{key} is required'
                return Response({"error": error_message}, status=400)

        return Response({"message": "all params are present"}, status=200)
zkure5ic

zkure5ic3#

DRF中没有支持验证的库。您必须为请求字段验证编写自定义代码。
您还可以编写序列化程序类来验证请求字段参数。

相关问题