gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:32:11 27 4
gpt4 key购买 nike

概述


带有查询参数的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com