Django - 在没有变量之一的情况下重建查询字符串
我有一个处理 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()
但我相信这可能是一个更好的解决方案:
>>> 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()
有人能想到更好的方法吗?
I have a Django view that processes a GET request. I want to rebuild the query string to include all variables except for one.
I was initially using list comprehension:
>>> 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()
But I believe this may be a better solution:
>>> 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()
Can anyone think of an even better approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Django 将 GET 请求变量放入字典中,因此 request.GET 已经是一个 QueryDict。你可以这样做:
请注意,python 中的字典(和 django QueryDicts)没有 del() 方法,你必须使用 python 内置的 del() 函数。 QueryDict 是不可变的(但它们的副本不是),因此您在尝试删除它之前复制它是正确的。另外,在最后一行中, z.urlencode() 返回一个字符串,它不会将 z 转换为 url 编码的字符串,因此您需要将其分配给另一个变量,以便稍后对其进行处理。
希望有帮助
Django puts the GET request variables into a dictionary for you, so request.GET is already a QueryDict. You can just do this:
Note that dictionaries in python (and django QueryDicts) don't have a del() method, you have to use python's built in del() function. QueryDicts are immutable (but copies of them are not), so you were right to copy it before trying to delete from it. Also, in your last line z.urlencode() returns a string, it doesn't convert z to a url encoded string, so you need to assign it to another variable in order to do something with it later.
Hope that helps
顶级方法绝对是最好的。我一直认为你的第二个(下面的)例子是你最新的例子,并且完全困惑了。
我什至无法想象另一种方法,除非我们开始做我们不应该做的事情,例如将
_mutable
属性设置为False
而不是copy()< /代码>。
注意:这是为了搞笑,实际上不要这样做
2110003 个函数调用需要 2.117 CPU 秒
3010003 个函数调用需要 3.065 CPU 秒
2860003 个函数调用需要 3.388 CPU 秒
The top approach is definitely as good as it gets. I kept thinking your second (lower) example was your newest one and was thoroughly confused.
I can't even imagine another method unless we start doing stuff we're not supposed todo, like setting the
_mutable
attribute toFalse
instead ofcopy()
.Note: this is for shits and giggles, don't actually do this
2110003 function calls in 2.117 CPU seconds
3010003 function calls in 3.065 CPU seconds
2860003 function calls in 3.388 CPU seconds