标签:
利用django的Q()功能可以很好的展开搜索功能
假设我要做个这样的搜索功能
那么思路是怎么样的?
前端获取 --》输入 --》ajax后台获取 --》进行搜索 --》将值返回后台 ---》ajax在进行处理传到页面
那我们就来看看代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .left{ float: left; } .clearfix:after{ content: ‘.‘; clear: both; display: block; visibility: hidden; height: 0; } </style> </head> <body> <div class="condition"> <div class="item clearfix"> <div class="icon left" onclick="AddCondition(this);">+</div> <div class="left"> <select onchange="ChangeName(this);"> <option value="name">书名</option> <option value="book_type__caption">图书类型</option> <option value="price">价格</option> <option value="pages">页数</option> </select> </div> <div class="left"><input type="text" name="name" /></div> </div> </div> <div> <input type="button" onclick="Search();" value="搜索" /> </div> <div class="container"></div> <script src="/static/js/jquery-1.12.4.js"></script> <script> function AddCondition(ths) { var new_tag = $(ths).parent().clone();//克隆 new_tag.find(‘.icon‘).text(‘-‘); //更改+ 为- new_tag.find(‘.icon‘).attr(‘onclick‘, ‘RemoveCondition(this);‘); //属性什么等于什么 $(ths).parent().parent().append(new_tag);//添加 } function RemoveCondition(ths) {//删除 $(ths).parent().remove(); } function ChangeName(ths) {//改变名称就触发 var v = $(ths).val();//得到值 $(ths).parent().next().find(‘input‘).attr(‘name‘,v);//改变属性name的值为v } function Search() { var post_data_dict = {};//定义一个{} // 获取所有input的内容,提交数据 $(‘.condition input‘).each(function () {//循环 // console.log($(this)[0]) var n = $(this).attr(‘name‘);//得到属性值 var v = $(this).val();//得到val值 var v_list = v.split(‘,‘);//,分割 post_data_dict[n] = v_list;//定义一个列表 }); console.log(post_data_dict); var post_data_str = JSON.stringify(post_data_dict); $.ajax({ url: ‘/app03/index/‘, type: ‘POST‘, data: { ‘post_data‘: post_data_str}, dataType: ‘json‘,
success: function (arg) { // 字符串 "<table>" + if(arg.status){ var table = document.createElement(‘table‘); table.setAttribute(‘border‘,1); // [{,name,pubdate,price,caption},] $.each(arg.data, function(k,v){ var tr = document.createElement(‘tr‘); var td1 = document.createElement(‘td‘); td1.innerText = v[‘name‘]; var td2 = document.createElement(‘td‘); td2.innerText = v[‘price‘]; var td3 = document.createElement(‘td‘); td3.innerText = v[‘book_type__caption‘]; var td4 = document.createElement(‘td‘); td4.innerText = v[‘pubdate‘]; tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3); tr.appendChild(td4); table.appendChild(tr); }); $(‘.container‘).empty(); $(‘.container‘).append(table); }else{ alert(arg.message); } } }) } </script> </body> </html>
import json from datetime import date from datetime import datetime from decimal import Decimal class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field, datetime): return field.strftime(‘%Y-%m-%d %H:%M:%S‘) elif isinstance(field, date): return field.strftime(‘%Y-%m-%d‘) elif isinstance(field, Decimal): return str(field) else: return json.JSONEncoder.default(self, field) def index(request): if request.method == ‘POST‘: ret = {‘status‘: False, ‘message‘: ‘‘, ‘data‘:None} try: post_data = request.POST.get(‘post_data‘,None) post_data_dict = json.loads(post_data) print(post_data_dict) # {‘name‘: [‘11‘, ‘sdf‘],‘price‘: [‘11‘, ‘sdf‘]} # 构造搜索条件 from django.db.models import Q con = Q() for k,v in post_data_dict.items(): q = Q() q.connector = ‘OR‘ for item in v: q.children.append((k, item)) con.add(q, ‘AND‘) """ ret = models.Book.objects.filter(con) print(ret) # queryset,[对象] #就是上面是列表 from django.core import serializers #这种方法是django的自己的序列化方法,但是有个缺点,下面这句的ret只能是对象,所以只能用第二种方式 data = serializers.serialize("json", ret) print(type(data),data) # 字符串 """ """ #ret = models.Book.objects.filter(con).values(‘name‘,‘book_type__caption‘) ret = models.Book.objects.filter(con).values_list(‘name‘, ‘book_typ__ecaption‘) print(ret,type(ret)) li = list(ret) #这种方式也有一个缺点,就是date和小数的时候不能序列化,所以需要自定义类并继承 data = json.dumps(li) print(data,type(data)) """ print(type(con)) result = models.Book.objects.filter(con).values(‘name‘,‘price‘,‘pubdate‘,‘book_type__caption‘) # ret = models.Book.objects.filter(con).values_list(‘name‘, ‘book_type__caption‘) li = list(result) ret[‘status‘] = True ret[‘data‘] = li except Exception as e: ret[‘message‘] = str(e) ret_str = json.dumps(ret, cls=JsonCustomEncoder) return HttpResponse(ret_str) return render(request, ‘input.html‘)
标签:
原文地址:http://www.cnblogs.com/renfanzi/p/5815400.html