我有一个基本的搜索视图。它当前在数据库中查询来自特定客户端的任何对象。视图代码如下:
def search_page(request):
form = PrdSearchForm()
prdlinks = []
show_results = True
if request.GET.has_key('query'):
show_results = True
query = request.GET['query'].strip()
if query:
form = PrdSearchForm({'query' : query})
prdlinks = \
ProjectRecord.objects.filter(client__icontains=query)
if len(prdlinks) >= 1:
records = ProjectRecord.objects.filter(client__icontains=query)
t = get_template('org_list_client.html')
html = t.render(Context({'records': records}))
return HttpResponse(html)
else:
tpl = "prd_search.html"
variables = RequestContext(request, { 'form': form,
'prdlinks': prdlinks,
'show_results': show_results})
return render_to_response(tpl, variables)
我希望搜索字段按客户端和帐户检查对象。我认为,这将涉及更改此代码:
if query:
form = PrdSearchForm({'query' : query})
prdlinks = \
ProjectRecord.objects.filter(client__icontains=query)
包括ProjectRecord.objects.filter(account__icontains=query)
。任何人都可以帮助解决语法问题,还是更多地涉及到我想要完成的任务?
答案 0 :(得分:2)
我认为你正在寻找Q
对象(由MYYN引用)
from django.db.models import Q
records=ProjectRecord.objects.filter(
Q(client__icontains=query) |
Q(account__icontains=query)
)
答案 1 :(得分:1)
您可以尝试chain filters,例如:
>>> ProjectRecord.objects.filter(
... client__icontains=query).filter(account__icontains=query)
这将首先过滤包含查询的客户端,然后过滤此结果查询集,其中该帐户还包含查询。
一般表格:
>>> Entry.objects.filter(
... headline__startswith='What'
... ).exclude(
... pub_date__gte=datetime.now()
... ).filter(
... pub_date__gte=datetime(2005, 1, 1)
... )
其他有用的示例包含在文档中:
答案 2 :(得分:0)
重新构建视图代码,将客户记录(prdlinks)与帐户记录(acclinks)分开并单独处理。不确定它是否可行(确实如此)并且仍然不确定这是否是编写代码的最有效方式(可能不是)。无论如何,这是修改后的代码:
def search_page(request):
form = PrdSearchForm()
prdlinks = []
**acclinks = []**
show_results = True
if request.GET.has_key('query'):
show_results = True
query = request.GET['query'].strip()
if query:
form = PrdSearchForm({'query' : query})
prdlinks = \
ProjectRecord.objects.filter(client__icontains=query)
**acclinks = \
ProjectRecord.objects.filter(account__icontains=query)**
if len(prdlinks) >= 1:
records = ProjectRecord.objects.filter(client__icontains=query)
t = get_template('org_list_client.html')
html = t.render(Context({'records': records}))
return HttpResponse(html)
**elif len(acclinks) >= 1:
records = ProjectRecord.objects.filter(account__icontains=query)
t = get_template('org_list_account.html')
html = t.render(Context({'records': records}))
return HttpResponse(html)**
else:
tpl = "prd_search.html"
variables = RequestContext(request, { 'form': form,
'prdlinks': prdlinks,
'show_results': show_results})
return render_to_response(tpl, variables)