简体   繁体   English

在Django中进行多字段搜索

[英]Making a multiple field search in Django

I am trying to make a search page that searches for model objects using three fields corresponding to different pieces of data. 我正在尝试创建一个搜索页面,该页面使用对应于不同数据的三个字段来搜索模型对象。 Here is my code below: 这是我的代码如下:

models.py models.py

class Schedules(models.Model):
    course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
    start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
    instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')

views.py views.py

def search_Schedule(request):
    context_dict = {}
    if request.method == 'POST':
        query1 = request.POST['course_name_search']
        query2 = request.POST['start_date_search']
        query3 = request.POST['instructor_search']
        if query1:
            results = Schedules.objects.filter(course_name__icontains=query1)
            if query2:
                results = results.filter(start_time=query2)
                if query3:
                    results = results.filter(instructor__icontains=query3)
                    table = ScheduleTable(results)
                    if results.count():
                        context_dict['table'] = table
                    else:
                        context_dict['no_results'] = query1 + ", " + query2 + ", and " + query3
                else:
                    table = ScheduleTable(results)
                    if results.count():
                        context_dict['table'] = table
                    else:
                        context_dict['no_results'] = query1 + " and " + query2
            elif query3:
                results = results.filter(start_time__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + " and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1
        elif query2:
            results = Schedules.objects.filter(start_time=query2)
            if query3:
                results = results.filter(instructor__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query2 + " and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query2
        elif query3:
            results = Schedules.objects.filter(instructor__icontains=query3)
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query3
    return render(request, "schedule/search_schedule.html", context_dict)

search_schedule.html search_schedule.html

{% block main_content %}
    <form method="post" action="">
        {% csrf_token %}
        <label for="course_name_search">Course Name:</label>
        <input type="text" name="course_name_search" id="course_name_search">

        <label for="start_date_search">Start Date:</label>
        <input type="datetime" name="start_date_search" id="start_date_search">

        <label for="instructor_search">Instructor:</label>
        <input type="text" name="instructor_search" id="instructor_search"><br>
        <input type="submit" name="submit">
    </form>
    <div id="result_panel">
        {% if table %}
            {% render_table table %}
        {% else %}
            {% if no_results %}
                No results returned for <q>{{ no_results }}</q>
            {% else %}
                Please enter a search
            {% endif %}
        {% endif %}
{% endblock %}

For some reason, the search will work if I type in the course name field OR the instructor field, but won't work if I type in more than one field. 由于某些原因,如果我在课程名称字段或教师字段中键入内容,搜索将起作用,但如果我输入了多个字段,则搜索将不起作用。 And for some reason, the start date field will not work period, no matter how I type the date. 由于某种原因,无论我如何键入日期,开始日期字段都将无法使用。 Can somebody possibly help me with the correct way to type the code? 有人可以帮我输入正确的代码吗? Thank you. 谢谢。

try this if it works. 如果可行,请尝试此操作。

def search_Schedule(request):
context_dict = {}
if request.method == 'POST':
    query1 = request.POST.get('course_name_search',None)
    query2 = request.POST.get('start_date_search',None)
    query3 = request.POST.get('instructor_search',None)
    if query1:
        results = Schedules.objects.filter(course_name__icontains=query1)
        if query2:
            results = results.filter(start_time=datetime.datetime.strptime(query2, "%d%m%Y").date())
            if query3:
                results = results.filter(instructor__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + ", " + query2 + ", and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + " and " + query2
        elif query3:
            results = results.filter(instructor__icontains=query3)   #changed this filter condition
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query1 + " and " + query3
        else:
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query1
    elif query2:
        results = Schedules.objects.filter(start_time=datetime.datetime.strptime(query2, "%d%m%Y").date())
        if query3:
            results = results.filter(instructor__icontains=query3)
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query2 + " and " + query3
        else:
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query2
    elif query3:
        results = Schedules.objects.filter(instructor__icontains=query3)
        table = ScheduleTable(results)
        if results.count():
            context_dict['table'] = table
        else:
            context_dict['no_results'] = query3
return render(request, "schedule/search_schedule.html", context_dict)

You could try a drill-down method for your filtering to minimize your if statements: 您可以尝试使用向下钻取方法进行过滤,以最大程度地减少if语句:

course_name_search = request.POST.get('course_name_search', None)
start_date_search = request.POST.get('start_date_search', None)
instructor_search = request.POST.get('instructor_search', None)

queryset = Schedules.objects.all()

if course_name_search:
    queryset = queryset.filter(course_name__icontains=course_name_search)
if start_date_search:
    queryset = queryset.filter(start_date=start_date_search)
if instructor_search:
    queryset = queryset.filter(instructor__icontains=instructor_search)

# if none of the search params were filled in then return none
if not course_name_search and not start_date_search and not instructor_search:
    queryset = Schedules.objects.none()

But a few caveats here, and something to help your issue with the start dates, since you are reading the POST data directly you'll need to convert your start_date_search into an actual date before you query. 但是这里有一些警告,还有一些可以帮助您解决开始日期的问题,因为您直接读取POST数据,因此需要在查询之前将start_date_search转换为实际日期。

The other thing that will help you is it might be better to use a GET instead of a POST, which you can then read in the template to fill in the chosen values that you now fill into the 'no_results'. 另一个对您有帮助的事情是,最好使用GET而不是POST,然后您可以读取模板以填写所选的值,现在将这些值填充到“ no_results”中。

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

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