在查询字符串中添加或替换参数

时间:2021-09-01 13:17:05

It seems there's no way to capture the whole query string in Django, doesn't it? I've only the solutions for capturing individual parameters.

似乎没有办法在Django中捕获整个查询字符串,不是吗?我只有捕获个别参数的解决方案。

So how can I check whether the query string exists

那么如何检查查询字符串是否存在

I want to check whether the query string itself exists (any parameters after "?"), if it does then either replace or add the parameters "param1" to it. How can I do that? For example:

我想检查查询字符串本身是否存在(“?”之后的任何参数),如果确实如此,则替换或添加参数“param1”。我怎样才能做到这一点?例如:

  localhost:8000 -> localhost:8000/?param1=a
  localhost:8000/?param1=1 -> localhost:8000/?param1=bb
  localhost:8000/?param1=1&param2=fdfd -> localhost:8000/?param1=333&param2=fdfd

  localhost:8000/?param2=fdfd -> localhost:8000/?param1=1&param2=fdfd

How can I do that?

我怎样才能做到这一点?

1 个解决方案

#1


1  

request.GET is is the query string, and it conforms to the dictionary interface. As with all Python containers, an empty dict is False in a boolean context. So you can check if it's empty by just doing if request.GET.

request.GET是查询字符串,它符合字典界面。与所有Python容器一样,布尔上下文中的空dict为False。所以你可以通过request.GET来检查它是否为空。

However, in your examples it seems you're always replacing param1 anyway, do there is no need to check it first: just set the value: request.GET['param1'] = 'whatever'.

但是,在你的例子中,你似乎总是更换param1,不需要先检查它:只需设置值:request.GET ['param1'] ='whatever'。

#1


1  

request.GET is is the query string, and it conforms to the dictionary interface. As with all Python containers, an empty dict is False in a boolean context. So you can check if it's empty by just doing if request.GET.

request.GET是查询字符串,它符合字典界面。与所有Python容器一样,布尔上下文中的空dict为False。所以你可以通过request.GET来检查它是否为空。

However, in your examples it seems you're always replacing param1 anyway, do there is no need to check it first: just set the value: request.GET['param1'] = 'whatever'.

但是,在你的例子中,你似乎总是更换param1,不需要先检查它:只需设置值:request.GET ['param1'] ='whatever'。