python 之 Django 小案例

一, F  Q

   # F 使用查询条件的值
    #
    # from django.db.models import F
    # models.Tb1.objects.update(num=F('num')+1)

    # Q 构建搜索条件
    from django.db.models import Q
    # con = Q()
    #
    # q1 = Q()
    # q1.connector = 'OR'
    # q1.children.append(('id', 1))
    # q1.children.append(('id', 10))
    # q1.children.append(('id', 9))
    #
    # q2 = Q()
    # q2.connector = 'OR'
    # q2.children.append(('c1', 1))
    # q2.children.append(('c1', 10))
    # q2.children.append(('c1', 9))
    #
    # con.add(q1, 'AND')
    # con.add(q2, 'AND')
    #
    # models.Tb1.objects.filter(con)

    #
    # from django.db import connection
    # cursor = connection.cursor()
    # cursor.execute("""SELECT * from tb where name = %s""", ['Lennon'])
    # row = cursor.fetchone()

 Django基于Q 实现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/jquery-1.9.1.min.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);
        }
        function Search() {
            var post_data_dict = {};

            // 获取所有input的内容,提交数据
            $('.condition input').each(function () {
                // console.log($(this)[0])
                var n = $(this).attr('name');
                var v = $(this).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: '/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>
index.html
from django.shortcuts import render,HttpResponse
from app01 import models
# Create your views here.
import json
def test(request):
    # models.BookType.objects.create(caption='技术')
    # models.BookType.objects.create(caption='文学')
    # models.BookType.objects.create(caption='动漫')
    # models.BookType.objects.create(caption='男人装')

    # models.Book.objects.create(name='文艺复兴',pages='100',price='40',pubdate='1992-11-2',book_type_id='1')
    # models.Book.objects.create(name='解密',pages='80',price='10', pubdate='2016-6-10',book_type_id='2')
    # models.Book.objects.create(name='刀锋',pages='50',price='3', pubdate='2014-02-16',book_type_id='2')
    # models.Book.objects.create(name='查令十字路84号',pages='260',price='40',pubdate='1999-10-12',book_type_id='3')
    # models.Book.objects.create(name='红楼',pages='1000',price='500', pubdate='1760-1-1',book_type_id='3')
    # models.Book.objects.create(name='将夜',pages='2000',price='300', pubdate='2010-3-3',book_type_id='1')
    # models.Book.objects.create(name='mysql从删库到跑路',pages='20',price='10',pubdate='1998-9-2',book_type_id='4')
    # models.Book.objects.create(name='马克思主义',pages='50',price='100',pubdate='1937-3-3',book_type_id='2')

    return HttpResponse('ok')

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':
        print(request.POST.get('post_data',None))
        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,type(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:
                    print(v,type(v))
                    q.children.append((k, item))
                con.add(q, 'AND')
            """
            ret = models.Book.objects.filter(con)
            print(ret) # queryset,[对象]

            from django.core import serializers
            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_type__caption')# 列表里面以元组的形式
            #
            # li = list(ret)
            # data = json.dumps(li)
            # print(data,type(data))
            """
            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, 'index.html')
Views.py
from django.db import models

# Create your models here.
class Author(models.Model):
    name = models.CharField(max_length=20)
    age = models.IntegerField()

class BookType(models.Model):
    caption = models.CharField(max_length=64)

class Book(models.Model):
    name = models.CharField(max_length=64)
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    pubdate = models.DateField()


    book_type = models.ForeignKey(BookType)
models
# 注意这个 是django自带的序列化 但是它不支持时间 小数等格式
            ret = models.Book.objects.filter(con)
            print(ret) # queryset,[对象]

            from django.core import serializers
            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_type__caption')# 列表里面以元组的形式
            #
            # li = list(ret)
            # data = json.dumps(li)
            # print(data,type(data))

 

posted @ 2016-08-25 00:47  王志康  阅读(760)  评论(0编辑  收藏  举报