如何解决在Django中处理URL中的多个参数
在我的应用中,我试图通过URL查询多个参数,如下所示:
/allot-graph/?sc=Infac%20India%20Pvt.ltd&type=FLC
有2个参数sc
和type
有时它们也可以为空
我正在按如下方式处理单个参数:
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)
解决方法
您可以将 .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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。