首页 > 解决方案 > 我可以使用 django 从我的模型中的多个数据库中搜索吗?

问题描述

我有这个代码并且工作完美..但我想在我的所有模型中搜索如何做到这一点?

有什么想法吗?

我的代码

模型.py:

class OpratingSystems(models.Model):
# def etc .. 
class AndroidGames(models.Model):
# def etc ..
class Antivirus(models.Model):
# def etc ..
class AndroidApks(models.Model):
# def etc ..
class PCgames(models.Model):
# def etc ..
class PCprogram(models.Model):
# def etc ..
class Homepage(models.Model):
# def etc ..

视图.py:

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

        if query is not None:
            lookups= Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)

            results= Homepage.objects.filter(lookups).distinct()


            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页面:

     {% 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 %}

这是我的代码并在 Homeoage 模型中工作,那么如何使用所有模型?

标签: pythondjangopython-3.xdjango-modelsdjango-views

解决方案


一种解决方案是使用 filter() 方法,然后将所有查询与 itertools.chain 组合在一起

if query is not None:

   query1 =Model1.objects.filter(title__icontains=query)
   query2 = Model2.objects.filter(modelfield__icontains=query)
....

#now you can combine all queries with this chain method

   from itertools import chain
   results= list(chain(query1,query2...)

推荐阅读