问题描述
我想创建一个搜索面板。有很多字段需要填写,如果用户不填写,我想从数据库中选择该参数的所有记录。
我想知道如何在Django模型中这样做吗?在原始MySQL中,这很容易,但是我现在不介绍如何设置条件,例如
是否存在最佳做法对于此类问题?
预先感谢
让我们以 Blogpost
项目为例,在该项目中,我有一个 index.html
页面以使用渲染我的数据。因此,要搜索该数据,我将使用 。
在此 BlogView
中,您可以看到我指定了 query
,如果我们在请求中得到 q
,则表示 query
不为空因此它将运行 Filter
方法,其中使用容器
我可以要求指定要查找的内容,例如本例中的标题。 / p>
别忘了使用双下划线 __
>,也称为 dunder
def BlogView(request):
查询=请求.GET.get( q,None)
Blog = PostModel.objects.all()
如果查询不是None:
blog = blog.filter(
Q(title__icontains = query)|
Q(content__icontains = query)
)
context = {
queryset:博客,
}
模板=‘blog / index.html’
返回渲染(请求,模板,上下文)
I want to create a search panel. There will be many fields to fill out and if user doesn't fill out something I want to select all records from database for this parameter.
And I am wondering how to do this in django model ? In raw MySQL that'd be ease, but I don't now how to set up conditions, for example ,
Are there best practices for this kind of problem ?
Thanks in advance,
Lets take the example of Blogpost
project where i have a index.html
page to render my data by using. So to search in that data i will use Field lookups.
In this BlogView
you can see i specify query
, where if we get q
in request it means query
is not empty so it will run the Filter
method where using icontains
i can ask specify what to lookup e.g title in my case.
Don't forget to use Double-Underscore __
, also referred as dunder
def BlogView(request):
query = request.GET.get("q", None)
blog = PostModel.objects.all()
if query is not None:
blog = blog.filter(
Q(title__icontains=query) |
Q(content__icontains=query)
)
context = {
"queryset": blog,
}
template = 'blog/index.html'
return render(request, template, context)
这篇关于如何在Django中创建搜索模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!