简体   繁体   English

如何从URL查询字符串中找不到空变量? 或者我们可以从python中的请求获取URL查询字符串中的变量

[英]How to find not null variables from URL query string? or can we get the variable in URL query string from request in python

I want to filter data based on multiple fields in Django python. 我想基于Django python中的多个字段过滤数据。
The scenario is, if a GET request to webserver comes as /searchStudent/?firstName=&lastName=xyzage=23&class=&city= and we dont know what can be the possible parameter in query string, some of them can come with value and some variable doesnot comes with value. 场景是,如果对webserver的GET请求为/searchStudent/?firstName=&lastName=xyzage=23&class=&city= ,我们不知道查询字符串中可能的参数是什么,其中一些可以带有值和一些变量没有价值。 The question is, is there any to get the variable which have only value or which dont have values from request. 问题是,是否有任何获取只有值或者没有来自请求的值的变量。 I know we can simply getting value by using request.GET.get('city') but I am finding way for getting the non null variable from query string, is there any way to find the non value variable from query string? 我知道我们可以通过使用request.GET.get('city')来获取价值,但我找到了从查询字符串中获取非null变量的方法,有没有办法从查询字符串中找到非值变量? In above scenario city, class, and firstName doesn't have values and I dont want to add it on filter. 在上面的场景中, city, class, and firstName没有值,我不想在过滤器上添加它。 what will be the right approach? 什么是正确的方法? please suggest the right way. 请建议正确的方法。

To get a dict of non-empty query parameters use this code: 要获取非空查询参数的dict,请使用以下代码:

non_empty_params = dict((field, value)
                        for field, value in request.GET.iteritems() if value)

But do not build queryset this way. 但是不要这样构建queryset。 You should never ever trust data from the user input. 您永远不应该信任来自用户输入的数据。 So you have to have a list of fields to search and use this list to filter out incorrect field names: 因此,您必须有一个要搜索的字段列表,并使用此列表过滤掉不正确的字段名称:

fields = ('firstName', 'lastName', 'age', 'class', 'city', )
filter_params = dict((field, value)
                        for field, value in request.GET.iteritems()
                        if value and field in fields)
students = Student.objects.filter(**filter_params)

I did this way and I get answer for filtering dynamically 我这样做了,我得到了动态过滤的答案

filter_args={}
if request.GET.get('firstName') :
    filter_args['firstName']=request.GET.get('firstName')
if request.GET.get('lastName') :
    filter_args['lastName']=request.GET.get('lastName')
if request.GET.get('city') :
    filter_args['city']=request.GET.get('city')
Student.object.filter(**filter_args)

This is know as Dynamic Queries, I was not aware with this. 这被称为动态查询,我不知道这一点。 Thanks @catavaran, for suggesting concept. 感谢@catavaran,提出了概念。
also refered this link Dynamic Django Queries 也提到了这个链接动态Django查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM