首页 > 解决方案 > 如何使用 django 在多模型中搜索

问题描述

我想从数据库中的所有模型中搜索,所以我为此创建了这个搜索功能......但总是我得到'没有这个搜索的结果'如何解决这个问题?

视图.py:

def search(request):
if request.method == 'GET':
    query= request.GET.get('q')
    submitbutton= request.GET.get('submit')


    if query is not None:

        home_database= Homepage.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
        pcprograms_database= PCprogram.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
        androidapk_database= AndroidApks.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
        androidgames_database= AndroidGames.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
        antiruvs_database= Antivirus.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
        systems_database= OpratingSystems.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
        pcgames_database= PCgames.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)

        results= list(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database))



        context={'results': results,
                 'submitbutton': submitbutton}

        return render(request, 'html_file/enterface.html', context)

    else:
        return render(request, 'html_file/enterface.html')

else:
    return render(request, 'html_file/enterface.html')

html搜索表单:

   <form id="search_form" action="{% url 'search' %}" method="GET" value="{{request.GET.q}}">
    <input id="search_box" type="text" name="q" value="{{request.GET.q}}"
              placeholder=" Search For ... "/>
    <input id="search_button" type="submit" name="submit" value="Search"/>
</form>

.html 文件:

     {% if submitbutton == 'Search' and request.GET.q != '' %}
 {% if results %}
 <h1> <small> Results for </small><b>{{ request.GET.q }}</b> : </h1>
 <br/><br/>

 {% for result in results %}
 <label id="label_main_app"> <img id="img_main_app_first_screen" src="{{result.app_image.url}}" alt="no image found !" height="170" width="165" > {{result.name}} <br><br> <p id="p_size_first_page"> {{result.app_contect}} <br> <br> <a href="{{ result.page_url }}" type="button" class="btn btn-primary"><big> See More & Download </big>  </a> </p>
  </label>


 {% endfor %}
 {% else %}
 <h3> No results for this search </h3>
 {% endif %}
 {% endif %}

请问有什么帮助吗?

标签: pythondjangopython-3.xdjango-modelsdjango-rest-framework

解决方案


如果您尝试使用您需要Q的多个模型字段进行过滤django.db.models

Homepage.objects.filter(Q(name__icontains=query)&Q(app_contect__icontains=query),....

推荐阅读