简体   繁体   English

如何在Django中优化初始查询?

[英]How to refine an initial query in Django?

Following the reply to this question (Thanks again Ellie P!) I created a search page and a results page. 在回答了这个问题之后 (再次感谢Ellie P!),我创建了一个搜索页面和一个结果页面。

For instance if you search for the lawyer "delelle" the result page shows her firm, school and year graduated. 例如,如果您搜索律师“ delelle”,则结果页面将显示其律师行,学校和毕业年份。 But instead of displaying her info, I want to display other lawyers who graduated from the same school the same year. 但是,我不想显示她的信息,而是要显示其他同一年从同一所学校毕业的律师。

This is the view: 这是视图:

def search(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        lawyers = Lawyer.objects.filter(last__icontains=q)
        return render_to_response('search_results.html', {'lawyers': lawyers, 'query': q})
    else:
        return HttpResponse('Please submit a search term.')

Can anyone help me understand how I can save the school and year_graduated from the initial query and do a school and year_graduated search and display that result? 谁能帮助我了解如何从初始查询中保存schoolyear_graduated ,并进行schoolyear_graduated搜索并显示结果?

Thank you! 谢谢!

Edit 编辑

Model is here 模特在这里

Edit2 编辑2

I tried a few things from the QuerySet API 我尝试了QuerySet API的一些操作

Given the search query is "akira": 给定搜索查询为“ akira”:

>>> akira_year = Lawyer.objects.filter(first__icontains="Akira").values_list('year_graduated').order_by('year_graduated')

>>> print akira_year
[(u'2000',)]

But

>>> Lawyer.objects.filter(year_graduated__icontains=akira_year[0])
[]

doesn't work. 不起作用。

Can anyone help with the correct syntax to use in this case? 在这种情况下,谁能提供正确的语法帮助?

Thanks 谢谢

This view function answers the question: 此视图函数回答了以下问题:

def search(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        q_school = Lawyer.objects.filter(last__icontains=q).values_list('school', flat=True)
        q_year = Lawyer.objects.filter(last__icontains=q).values_list('year_graduated', flat=True)
        lawyers = Lawyer.objects.filter(school__icontains=q_school[0]).filter(year_graduated__icontains=q_year[0])        
        return render_to_response('search_results.html', {'lawyers': lawyers, 'query': q})
    else:
        return HttpResponse('Please submit a search term.')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM