【问题标题】:Handle multiple parameters from URL in Django在 Django 中处理来自 URL 的多个参数
【发布时间】:2021-02-02 22:57:54
【问题描述】:

在我的应用程序中,我试图从 URL 中查询多个参数,如下所示:

/allot-graph/?sc=Infac%20India%20Pvt.ltd&type=FLC

有两个参数sctype

有时它们也可能是空的

我正在处理单个参数,如下所示:

class AllotmentbyMonth(APIView):

    def get(self, request):
        q = 0
        try:
            q = request.GET['sc']
        except:
            pass

        if q == 0:

            print("q", q)

            dataset = Allotment.objects.all().annotate(
                month=TruncMonth('dispatch_date')).values(
                'month').annotate(c=Sum('flows__alloted_quantity')).values('month', 'c')
        else:
            print("q")
            client = Client.objects.filter(client_name = q)[0].pk
            print("client", client)
            dataset = Allotment.objects.filter(sales_order__owner=client).annotate(
                month=TruncMonth('dispatch_date')).values(
                'month').annotate(c=Sum('flows__alloted_quantity')).values('month', 'c')


        date = list(dataset)
        months = list()
        for i in date:
            months.append(i['month'].strftime("%B"))

        chart = {'chart': {'type': 'column', 'height': 400},

                 'title': {'text': 'Allotments by Months'},
                 'xAxis': {'categories': months},
                 'yAxis': {"title": {"text": 'Count'}},

                 'series': [{'name': 'Months', 'data': [{'name': row['month'], 'y': row["c"]} for row in dataset]}]}

        print("chart", chart)

        return Response(chart)

我知道这不是理想的方法,但这是我的解决方法。我该如何处理过滤器type,因为写太多if-else 似乎不对。

type 的过滤器是这样的:

.filter(flows__kit__kit_type = type)

【问题讨论】:

    标签: django django-queryset url-parameters


    【解决方案1】:

    您可以使用 .get(...) 方法作为

    class AllotmentbyMonth(APIView):
    
        def get(self, request):
            qp_sc = request.query_params.get("sc")
            qp_type = request.query_params.get("type")
    
            client_qs = Client.objects.all()
            if qp_sc:
                client_qs = client_qs.filter(some_field_name=qp_sc)

    由于您使用的是 DRF,所以最好使用 request.query_params 而不是 request.GET

    【讨论】:

    • 如果我同时拥有sctype 怎么办?
    猜你喜欢
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    相关资源
    最近更新 更多