python - 如何在 Django 中将查询参数动态设置为 request.GET

标签 python django http request

概述


带有查询参数的 url 看起来像。

http://example.api.com/search/?name=jhon&age=26

如果我正在使用 django-filter 则可以查看所有参数都是从请求中自动提取的,它将返回一个过滤后的查询集。

views.py

class SearchView(TemplateView):
   template_name = "search.html"

   def get_queryset(self):
       return SearchFilter(request.GET, queryset=Model.objects.all()).qs

   def get_context_data(self, **kwargs):
      context = super(SearchView, self).get_context_data(**kwargs)
      return context

如果我想从 request.GET 中手动提取它,我可以做到。

def get_queryset(self):
   # extracting query parameter 
   q = self.request.GET.get('name')

问题陈述


我的搜索 url 看起来像

 http://example.api.com/search/jhon-26

我这样做是因为我不想向公众透露像“姓名”和“年龄”这样的键,这是为了安全抽象,这些是我的数据库表的列。

我在 **kwargs 中得到 jhon-26,我想将它拆分并设置为 request.GET 的查询参数,以便我的过滤器类可以正常工作

问题


request.GET有没有设置属性?

# may be any set function available for this
self.request.GET.set('name', 'jhon')

我怎样才能做到这一点。

最佳答案

我找到了将查询参数设置为请求的解决方案。GET here

由于 request.GET QueryDict 实例是不可变的,因此我们不能直接修改它,因此我们需要将其 _mutable 属性设置为 True

if not request.GET._mutable:
   request.GET._mutable = True

# now you can edit it
request.GET['name'] = 'jhon'
request.GET['age'] = 26

关于python - 如何在 Django 中将查询参数动态设置为 request.GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45188800/

相关文章:

ajax - 什么 HTTP 谓词应该用于 POST 到外部 API 的 AJAX 请求?

node.js - NTLM 如何为 Web 服务工作以验证用户身份?

python - Facebook Python 登录脚本不使用 API

python - django 模型 select_lated 或 prefetch_lated 子模型

python - 与 Oauth 的 Django session - 无法通过 request.session 传递变量

django - 在自定义 500 处理程序中捕获错误文本

google-chrome - 为什么IE和Chrome显示的内容不一样?

python - 与 Raspberry Pi 的移动标志通信协议(protocol) v1.2

python - 在 aws 上运行 django 项目的最佳方式是什么?

python - sympy 中的矩阵运算错误