Django Q搜索
- 示例中知识点:
1. Q生成查询条件
2. json 序列化
3. 前段创建新标签
css:
*{ margin: 0px; padding: 0px; } input, button, textarea { outline: none; -webkit-appearance: none; border-radius: 0; } .search{ margin-left: 20px; margin-top: 20px; } .search .item{ margin-top: 10px; } .search .item .button{ width: 20px; text-align: center; } .search > input{ margin-top: 20px; padding: 5px; font-weight: bold; color: white; } table { border-collapse:collapse; } th { height:50px; } table, td, th { border:1px solid green; } th { background-color:green; color:white; } td { padding:15px; }
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link type="text/css" rel="stylesheet" href="/static/css/Q_search.css"> </head> <body> <div class="search"> <div class="item"> <input type="button" value="+" class="button"> <select> <option value="name">书名</option> <option value="book_type__name">图书类型</option> <option value="price">价格</option> </select> <input type="text" name='name'> </div> <input type="button" value="Search"> </div> <div class="result"> </div> <script src="/static/js/jquery-3.2.1.min.js"></script> <script src="/static/js/Q_search.js"></script> </body> </html>
js:
/** * Created by lenovo on 2017/11/11. */ $(document).ready(function () { // 增加条件 $('.search .item .button').bind('click', function () { var clone_label = $(this).parent().clone(); //console.log(clone_label[0]); // 为clone的标签绑定 click remove事件 $(clone_label).children('.button').attr('value','-').bind('click',function () { $(clone_label).remove(); }); // 为clone的标签绑定select change事件 $(clone_label).children('select').bind('change', function () { var v = $(clone_label).children('select').val(); $(clone_label).children('input').last().attr('name', v); //console.log(v) }) $(this).parent().after(clone_label); }); // 修改input的name的属性值 $('.search .item select').bind('change',function () { var ret = $('.search .item select option:selected').val(); $('.search .item input').last().attr('name', ret); }); // 发送ajax请求 $('.search > input').bind('click', function () { var input_dict = {}; $('.search .item input').not('.button').each(function () { //console.log($(this)[0]); var n = $(this).attr('name'); var v =$(this).val().split(','); //console.log(n, v) input_dict[n] = v; }); //console.log(input_dict) input_dict = JSON.stringify(input_dict); $.ajax({ url:'/app01/search/', type:'POST', data:{'post_data':input_dict}, success:function (data,statusText) { //console.log(data); var ret = JSON.parse(data); //console.log(ret['data']); //console.log(ret['data'].length); // 查询前清空上次查询结果 $('.result').empty(); var $_table = $('<table></table>'); $('.result').append($_table); // 生成tr标签 for(var i = 0;i < ret['data'].length; i++){ var $_tr = $('<tr></tr>'); $($_table).append($_tr); // 生成td标签 for(var j in ret['data'][i]){ var $_td = $('<td></td>'); $($_td).text(ret['data'][i][j]); $($_tr).append($_td); console.log(j); } } }, error:function () { console.log('send fail..') } }) }); })
后台:
def search(request): if request.method == 'POST': result_info = {'status': False, 'error_message': None, 'data': None} try: accept_value = request.POST.get('post_data', None) accept_value = json.loads(accept_value) # print(accept_value) # 创建Q条件 if accept_value: conn = Q() for k, v in accept_value.items(): q = Q() q.connector = 'OR' for item in v: q.children.append((k, item)) conn.add(q, 'AND') res = models.Book.objects.all().filter(conn).values('name', 'price', 'book_type__name') res_list = list(res) # 将queryset转成list print(res_list) result_info['data'] = res_list result_info['status'] = True except Exception as e: result_info['error_message'] = e # 将结果序列化,传给前段 data = json.dumps(result_info, cls=commons.JsonCustomEncoder) # print(data) return HttpResponse(data) """ # 通过Django的序列化功能,将queryset序列化为json格式发送给前段 ret = models.Book.objects.all().filter(conn) data = serializers.serialize("json", ret) print(data) # [{"model": "app01.book", "pk": 1, "fields": {"name": "python", "price": "20", "book_type": 1}}] """
json序列化,对不是python基本数据类型的进行序列化时
from datetime import datetime import json from datetime import date 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)