python - 使用多个查询的 Django 过滤
问题描述
在我的主页上,我有一个搜索栏,当您搜索某些内容时,它会将您重定向到包含结果(标题和文档类型)的页面。在页面的左侧,我想按文档类型实现过滤器。
搜索后我的网址如下所示:http://127.0.0.1:8000/search/?q=something
应用过滤器后:http://127.0.0.1:8000/search/?document_type=Tehnical+report
我不知道如何实现过滤器以仅在搜索页面上由查询 (q) 过滤的对象列表中进行搜索。另外,我不确定 url 是否应该像这样:http://127.0.0.1:8000/search/?q=something&document_type=Tehnical+report
或者http://127.0.0.1:8000/search/?document_type=Tehnical+report
在应用过滤器后像这样。
模型.py
DOCUMENT_TYPES = [
('Tehnical report','Tehnical report'),
('Bachelor thesis','Bachelor thesis'),
...
]
class Form_Data(models.Model):
title = models.CharField(unique=True, max_length=100, blank=False)
author = models.CharField(max_length=100)
document_type = models.CharField(choices=DOCUMENT_TYPES, max_length=255, blank=False, default=None)
视图.py
def search_list(request):
object_list = Form_Data.objects.none()
document_types = DOCUMENT_TYPES
query = request.GET.get('q')
query_list = re.split("\s|(?<!\d)[,.](?!\d)", query)
document_type_query = request.GET.get('document_type')
for item in query_list:
object_list |= Form_Data.objects.filter( Q(title__icontains=item) | Q(author__icontains=item))
return render(request, "Home_Page/search_results.html")
home_page.html
<div class="Search">
<form action="{% url 'home_page:search_results' %}" method="get">
<input id="Search_Bar" type="text" name="q">
<button id="Button_Search" type="submit"></button>
</form>
</div>
search_results.html
{% for form_data in object_list %}
<h5>{{ form_data.title }}</h5>
<h5>{{ form_data.document_type }}</h5>
{% endfor %}
<form method="GET" action=".">
<select class="form-control" name="document_type">
{% for tag, label in document_types %}
<option value="{{ tag }}">{{ tag }}</option>
{% endfor %}
</select>
</form>
解决方案
这将是模型过滤:
query = request.GET.get('q')
document_type_query = request.GET.get('document_type')
object_list = FormData.objects.none()
for item in query.split():
item_qs = FormData.objects.filter(Q(title__icontains=item) | Q(author__icontains=item))
if document_type_query:
item_qs = item_qs.filter(document_type=document_type_query)
object_list |= item_qs
return render(request, "Home_Page/search_results.html", {"object_list": object_list})
这是网址:
http://127.0.0.1:8000/search/?q=something%20with%20spaces&document_type=Tehnical+report
推荐阅读
- elasticsearch - 无法通过应用特定字段的过滤器获得类似结果
- python - 熊猫读取 csv 使用定界符固定时间
- mongodb - MongoDB查询今天和明天的事件
- reactjs - How to return text + icon from a function in React
- html - 计算创建具有给定对角线长度的菱形所需的正方形的边和斜度
- php - PHP $_POST 带有数组和 [ ] 键
- java - 我们可以在spring mvc中更改springBeanConfiguration文件的位置吗?
- jakarta-ee - CSRFGuard 在脚本标签中加载 javascript 注入
- spring-security - PreAuthenticatedAuthenticationProvider UserDetailsService 如何捕获正确的异常
- powerbi - 用于检查 Treemap 中多个选定值的 DAX 代码