Django - 重建没有其中一个变量的查询字符串

Bel*_*dez 9 python django django-views

我有一个处理GET请求的Django视图.我想重建查询字符串以包含一个之外的所有变量.

我最初使用列表理解:

>>> from django.http import QueryDict
>>> q = QueryDict('a=2&b=4&c=test') // <--- make believe this is request.GET
>>> z = QueryDict('').copy()
>>> z.update(dict([x for x in q.items() if x[0] != 'b']))
>>> z.urlencode()
Run Code Online (Sandbox Code Playgroud)

但我相信这可能是一个更好的解决方案:

>>> from django.http import QueryDict
>>> q = QueryDict('a=2&b=4&c=test') // <--- make believe this is request.GET
>>> z = q.copy()
>>> del z['b']
>>> z.urlencode()
Run Code Online (Sandbox Code Playgroud)

谁能想到更好的方法?

dan*_*nny 11

Django将GET请求变量放入字典中,因此request.GET已经是一个QueryDict.你可以这样做:

z = request.GET.copy()
del z['a']
Run Code Online (Sandbox Code Playgroud)

请注意,python(和django QueryDicts)中的字典没有del()方法,您必须使用python的内置del()函数.QueryDicts是不可变的(但它们的副本不是),因此在尝试从中删除之前,你是正确的.此外,在最后一行中,z.urlencode()返回一个字符串,它不会将z转换为url编码的字符串,因此您需要将其分配给另一个变量,以便稍后对其执行某些操作.

希望有所帮助


Yuj*_*ita 5

顶级方法绝对是最好的。我一直认为您的第二个(较低)示例是您最新的示例,并且完全困惑。

我什至无法想象另一种方法,除非我们开始做我们不应该做的事情,比如将_mutable属性设置为False而不是copy().

注意:这是为了开玩笑和傻笑,实际上不要这样做

2110003 次函数调用在 2.117 CPU 秒内

def test3(n):
    for i in range(n):
        q = QueryDict('a=2&b=4&c=test') # we could pass the mutable argument here 
        # but normally we wouldn't be constructing the querydict ourselves
        q._mutable = True
        del q['b']
        q.urlencode()
Run Code Online (Sandbox Code Playgroud)

3.065 CPU 秒内调用 3010003 次函数

 def test1(n):
    for i in range(n):
        q = QueryDict('a=2&b=4&c=test')
        z = q.copy()
        del z['b']
        z.urlencode()
Run Code Online (Sandbox Code Playgroud)

3.388 CPU 秒内 2860003 次函数调用

def test2(n):
    for i in range(n):
        q = QueryDict('a=2&b=4&c=test')
        z = QueryDict('').copy()
        z.update(dict([x for x in q.items() if x[0] != 'b']))
        z.urlencode()
Run Code Online (Sandbox Code Playgroud)