python - 我可以使用 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 模型中工作,那么如何使用所有模型?
解决方案
一种解决方案是使用 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...)
推荐阅读
- java - 当我们说tomcat服务器正在“运行”时是什么意思。幕后到底发生了什么
- javascript - React Redux - 提交时不会触发动作
- java - 唯一对象实例的Java Map?
- python - 我如何在数据框中划分这个文本文件?
- wordpress - 我们如何让 Wordpress 支持 .jfif 图片上传?
- react-native - 如何将数据发送到硬件上的先前路线按反应导航 5
- mongodb - MongoDB 存储 API 调用
- c# - 在 Blazor 中绑定使用 InputFile 选择的文件
- php - Opencart htaccess 以减少服务器响应时间和缓存
- android-layout - Xamarin.Android:水平滚动条不适用于 SfPulltoRefresh