【发布时间】:2019-06-20 07:49:08
【问题描述】:
我想在 django 应用程序中为我的数据库创建一个多字段搜索。 仅当用户使用 html 表单中的 all 字段时,我的搜索才能正常工作。
如果用户不使用某些字段或某些字段为空或空白
然后我的查询返回所有结果(如 apps=movies.objects.all() )这是错误的,因为用户不需要使用所有字段
但可以随时使用需要搜索的字段。
知道如何解决这个问题吗?
这是我的代码:
models.py:
class category(models.Model):
title = models.CharField(max_length=100, blank=True, null=True)
class movies(models.Model):
code = models.CharField(max_length=100, blank=True, null=True)
code_2 = models.CharField(max_length=100, blank=True, null=True)
name = models.CharField(max_length=100, blank=True, null=True)
year = models.CharField(max_length=100, blank=True, null=True)
movies_title=models.ForeignKey('category', blank=True, null=True)
link=models.CharField(max_length=100, blank=True, null=True)
html 表单:
<form method="POST" action="{%url 'search' %}">{% csrf_token %}
<select name="link">
<option value=""></option>
<option value="0">link 1</option>
<option value="1">link 2</option>
<option value="2">link 3</option>
</select>
<select name="category">
<option value=""></option>
{% for data in cat%}
<option value="{{ data.id }}">{{ data.title }}</option>
{% endfor %}
</select>
<select name="year">
<option value=""></option>
{% for data in apps%}
<option value="{{ data.id }}">{{ data.year }}</option>
{% endfor %}
</select>
code: <input type="text" name="code"><br>
code_2: <input type="text" name="code_2"><br>
name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
views.py:
def search_erga(request):
apps=movies.objects.all()
cat=category.objects.all()
template='movies.html'
query_link=request.GET.get('link')
query_category = request.GET.get('category')
query_year=request.GET.get('year')
query_code = request.GET.get('code')
query_code_2=request.GET.get('code_2')
query_name = request.GET.get('name')
if any(
(
query_link is not None,
query_category is not None,
query_year is not None,
query_code is not None,
query_code_2 is not None,
query_name is not None,
)
):
apps_1=movies.objects.filter(link__icontains=query_link,
movies_title__icontains=query_category,
year__icontains=query_year,
code__icontains=query_code,
code_2__icontains=query_code_2,
name__icontains=query_name)
context={
'apps':apps,
'cat':cat,
'apps_1':apps_1
}
else:
context={
'apps':apps,
'cat':cat,
}
return render(request, template, context)
【问题讨论】:
-
请看表单在 Django 中是如何工作的;你现在正在做大量不必要的工作。 docs.djangoproject.com/en/2.1/topics/forms
-
您还应该发布
movies.html。你如何处理apps和apps_1?您是否注意到您总是返回包含所有结果的apps?这是故意的吗?
标签: python html django forms search