如何为Django模板添加搜索栏? [英] How to add Search bar for django template?

查看:181
本文介绍了如何为Django模板添加搜索栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的桌子顶部的模板中需要一个搜索栏。搜索栏应基于任何表参数进行搜索,并相应地过滤输入内容。

I need a search bar in my template on top of my table. The search bar should search based on any table parameter, and filter the enteries accordingly.

我使用CSS类实现了搜索栏,并根据需要获得了它。
现在是views.py代码。

I implemented the search bar using CSS classes and I get it as I wanted. Now here's the views.py code.

def jobs(request):
    jobs = Jobb.objects.all()
    search_term = ''
    if 'search' in request.GET:
        search_term = request.GET['search']
        jobs = jobs.filter(position__icontains=search_term)
    context = {
        'jobs': jobs, 'search_term': search_term, 'job': 'active'
    }
    return render(request, 'Job_openings/jobb.html',context)

此代码对我有用,但问题是

This code does the job for me , but the problem is that it only searches the enteries based on my model return value.

def __str__(self):
    return self.position

因此,我只能搜索具有某些特定位置的所有小肠。

Thus, I'm only able to search all enteries having some specific 'position'.

我的模型还有其他字段,例如发布日期,公司名称。.
我希望搜索栏对所有此类字段都有效。
假设我输入了一个公司名称,然后从列表中得到了所有结果。

My model has other fields like 'date posted', 'company name'.. I want the search bar to work for all such fields. Lets say I enter a company name, and I get all the results from the list.

如何实现?

推荐答案

,您可以使用 Q对象以执行 OR查询。

you can use Q objects to perform "OR" queries.

from django.db.models import Q


jobs = jobs.filter(
    Q(position__icontains=search_term) |
    Q(your_other_field__icontains=search_term) |
    Q(....)
)

然后,您可以在模板中使用循环访问它,并使用点。访问以下字段:

then, in your template, you can access it with loop, and use dot "." to access the fields like:

{% for job_item in jobs %}
    {{ job_item.position }}, {{ job_item.your_other_field }}
{% endfor %}

这篇关于如何为Django模板添加搜索栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆