我有这段代码,工作完美..但是我想在我所有的模型中搜索该怎么做?
有什么想法吗?
我的代码
Models.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 ..
Views.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...)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句