Day20 Django之Model多對多、中間件、緩存、信號和分頁

1、Form補充javascript

class IndexForm(forms.Form):
    # c = [
    #     (1, 'CEO'),
    #     (2, 'CTO')
    # ]
    # 靜態字段,屬於IndexForm類,即便數據庫增長頁面不會顯示
    c = models.UserType.objects.all().values_list('id','caption')
    user_type_id = forms.IntegerField(widget=forms.Select(choices=c))
    # 須要加上構造方法
    def __init__(self, *args, **kwargs):
        #父類構造方法:1.獲取全部的靜態字段    2.fields = []
        super(IndexForm, self).__init__(*args, **kwargs)
        #print(self.fields['user_type_id'].widget.choices)
        self.fields['user_type_id'].widget.choices = models.UserType.objects.all().values_list('id','caption')

def index(request):
    form = IndexForm()
    return render(request, 'index.html', {'form':form})
views.py

2、數據操做之F/Qhtml

建立數據:java

def index(request):
    for i in range(10):
        models.UserType.objects.create(caption='CE'+str(i))
    c = models.UserType.objects.all().count()
    print(c)

導入F/Q:python

from django.db.models import F,Q

單表操做:mysql

q1 = Q()
    q1.connector = 'OR'
    q1.children.append(('id', 1))
    q1.children.append(('id', 2))
    q1.children.append(('id', 3))


    obj = models.UserType.objects.filter(q1)
    for item in obj:
        print(item.id, item.caption)

連表操做:sql

con = Q()
    q1 = Q()
    q1.connector = 'OR'
    q1.children.append(('id', 1))
    q1.children.append(('id', 2))
    q1.children.append(('id', 3))

    q2 = Q()
    q2.connector = 'OR'
    q2.children.append(('caption', 'CE1'))
    q2.children.append(('caption', 'CE2'))
    con.add(q1, 'AND')
    con.add(q2, 'AND')

    obj = models.UserType.objects.filter(con)
from django.shortcuts import render,HttpResponse
from django import forms
from app01 import models
from django.db.models import F,Q
import time
from django.views.decorators.cache import cache_page
# Create your views here.

class IndexForm(forms.Form):
    # c = [
    #     (1, 'CEO'),
    #     (2, 'CTO')
    # ]
    # 靜態字段,屬於IndexForm類,即便數據庫增長頁面不會顯示
    c = models.UserType.objects.all().values_list('id','caption')
    user_type_id = forms.IntegerField(widget=forms.Select(choices=c))
    # 須要加上構造方法
    def __init__(self, *args, **kwargs):
        #父類構造方法:1.獲取全部的靜態字段    2.fields = []
        super(IndexForm, self).__init__(*args, **kwargs)
        #print(self.fields['user_type_id'].widget.choices)
        self.fields['user_type_id'].widget.choices = models.UserType.objects.all().values_list('id','caption')

def index(request):
    # for i in range(10):
    #     models.UserType.objects.create(caption='CE'+str(i))
    # c = models.UserType.objects.all().count()
    # print(c)
    form = IndexForm()
    """
    q1 = Q()
    q1.connector = 'OR'
    q1.children.append(('id', 1))
    q1.children.append(('id', 2))
    q1.children.append(('id', 3))


    obj = models.UserType.objects.filter(q1)
    for item in obj:
        print(item.id, item.caption)
    """
    con = Q()
    q1 = Q()
    q1.connector = 'OR'
    q1.children.append(('id', 1))
    q1.children.append(('id', 2))
    q1.children.append(('id', 3))

    q2 = Q()
    q2.connector = 'OR'
    q2.children.append(('caption', 'CE1'))
    q2.children.append(('caption', 'CE2'))
    con.add(q1, 'AND')
    con.add(q2, 'AND')

    obj = models.UserType.objects.filter(con)

    for item in obj:
        print(item.id, item.caption)
    return render(request, 'index.html', {'form':form})
views.py

3、Model對多對操做數據庫

from django.db import models

# Create your models here.

class UserType(models.Model):
    caption = models.CharField(max_length=16)

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    user_type = models.ForeignKey('UserType')

#多對多
#本身建立
# class B2G(models.Model):
#     b_id = models.ForeignKey('Boy')
#     g_id = models.ForeignKey('Girl')

# 1    小明
# 2    小黑
# 3    小軍
class Boy(models.Model):
    username = models.CharField(max_length=16)

# 1    芳芳
# 2    珠珠
# 3    哈哈
class Girl(models.Model):
    name = models.CharField(max_length=16)
    #自動建立第三張表
    b = models.ManyToManyField('Boy')
models.py

方式一:本身建立django

class B2G(models.Model):
            b_id = models.ForeignKey('Boy')
            g_id = models.ForeignKey('Girl')

        class Boy(models.Model):
            username = models.CharField(max_length=16)

        class Girl(models.Model):
            name = models.CharField(max_length=16)

方式二:自動建立緩存

class Boy(models.Model):
            username = models.CharField(max_length=16)
            #girl_set

        class Girl(models.Model):
            name = models.CharField(max_length=16)
            b = models.ManyToManyField('Boy')

新增:session

正向:
    g1 = models.Girl.objects.get(id=1)
    b1 = models.Boy.objects.get(id=1)
    g1.b.add(b1)

    bs = models.Boy.objects.all()
    g1.b.add(*bs)
    g1.b.add(1)
    g1.b.add(*[1,2,3,4,5,6,7])


反向:
     b1 = models.Boy.objects.get(id=1)
     #因ManyToManyField因此隱含_set
     b1.girl_set.add(1)
     b1.girl_set.add(models.Girl.objects.all())

     b1.girl_set.add(*[1,2,3,4,5])

刪除:

g1 = models.Girl.objects.get(id=1)
            g1.b.clear()    #所有清空和girl ID=1所關聯的全部數據
            g1.b.remove(2)
            g1.b.remove(*[1,2])

查詢:

g1 = models.Girl.objects.get(id=1)  #SQL
g1.b.all()                          #SQL
g1.b.filter().count()

b1 = models.Boy.objects.get(id=1)
b1.girl_set.all()

models.Girl.objects.all().values('id', 'name','b__username')
models.Boy.objects.all().values('id', 'username','girl__name')

更新:

ORM:
    python操做數據庫模塊:
      MySQLdb
      pymysql
原生SQL:
from django.db import connection cursor = conection.cursor() cursor.execute("""SELECT * from tb where name = %s""", ['Lennon']) row = cursor.fetchone()

4、中間件

配置文件:
        MIDDLEWARE_CLASSES =
    寫類:
        process_request
        process_view
        process_exception
        process_response

    1.10
    配置文件:
        MIDDLEWARE =
    原版本:
        若是process_request中有return,則全部的process_response執行一遍
MIDDLEWARE = [
    'django.middleware.cache.UpdateCacheMiddleware',
    'md.sa.M1',
    'md.sa.M2',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
]

路徑:/project_dir/md/sa.py

from django.utils import deprecation
class M1(deprecation.MiddlewareMixin):
    def process_request(self, request):
        print('M1.process_request')

    def process_view(self, request, callback, callback_args, callback_kwargs):
        print('M1.process_view')

    def process_exception(self, request, exception):
        print('M1.process_exception')

    def process_response(self, request, response):
        print('M1.process_response')
        return response

    def process_template_response(self, request, response):
        print('M1.process_template_response')


class M2(deprecation.MiddlewareMixin):
    def process_request(self, request):
        print('M2.process_request')

    def process_view(self, request, callback, callback_args, callback_kwargs):
        print('M2.process_view')

    def process_exception(self, request, exception):
        print('M2.process_exception')

    def process_response(self, request, response):
        print('M2.process_response')
        return response

    def process_template_response(self, request, response):
        print('M2.process_template_response')
sa.py
def md(request):
    print('views.md')
    #return HttpResponse('ok')
    obj = HttpResponse('OK')
    #若是obj中有render方法則執行中間件的process_template_response
    #render(request,'index.html')
    #render_to_response('index')會執行process_template_response
    return obj

5、緩存

6種方式:

1.開發調試
2.內存
3.文件
4.數據庫
5.memcache緩存(python-memcached模塊)
6.memcache緩存(pylibmc模塊)
#單獨頁面緩存
#@cache_page(5)
def cache1(request):
    c = time.time()
    from Day20 import pizza_done
    pizza_done.send(sender='seven', toppings=123, size=456)
    return render(request, 'cache.html', {'c':c})
全站緩存
CACHES = {
    'default':{
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': os.path.join(BASE_DIR, 'cache')
    }
}
{% load cache %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>{{ c }}</h1>

    <div style="border: 1px solid red; height: 50px;">
        {% cache 5 views_h %}
            <h1>{{ c }}</h1>
        {% endcache %}
    </div>
</body>
</html>
cache.html

6、信號

對於Django內置的信號,僅需註冊指定信號,當程序執行相應操做時,自動觸發註冊函數:

from django.core.signals import request_finished
from django.core.signals import request_started
from django.core.signals import got_request_exception

from django.db.models.signals import class_prepared
from django.db.models.signals import pre_init, post_init
from django.db.models.signals import pre_save, post_save
from django.db.models.signals import pre_delete, post_delete
from django.db.models.signals import m2m_changed
from django.db.models.signals import pre_migrate, post_migrate

from django.test.signals import setting_changed
from django.test.signals import template_rendered

from django.db.backends.signals import connection_created


def callback(sender, **kwargs):
    print("xxoo_callback")
    print(sender,kwargs)


import django.dispatch
pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])

def callback1(sender, **kwargs):
    print("callback1")
    print(sender, kwargs)
pizza_done.connect(callback1)
__init__.py

自定義信號:

a. 定義信號

import django.dispatch
pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])

b. 註冊信號

def callback(sender, **kwargs):
    print("callback")
    print(sender,kwargs)
 
pizza_done.connect(callback)

c. 觸發信號

from 路徑 import pizza_done
 
pizza_done.send(sender='haha',toppings=456, size=789)

因爲內置信號的觸發者已經集成到Django中,因此其會自動調用,而對於自定義信號則須要開發者在任意位置觸發。

7、自定義分頁

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pager a{
            display: inline-block;
            padding: 5px;
            background-color: blue;
            margin: 2px;
        }
        .pager a.active{
            background-color: orangered;
        }
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>名稱</th>
            </tr>
        </thead>
        <tbody>
            {% for item in type_list %}
                <tr>
                    <td>{{ item.id }}</td>
                    <td>{{ item.caption }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    <div class="pager">
        {{ str_page }}
    </div>
</body>
</html>
page.html
def page(request):
    # for i in range(25, 100):
    #     models.UserType.objects.create(caption='CO'+str(i))
    current_page = request.GET.get('p',1)
    current_page = int(current_page)
    #每頁顯示10條數據
    #第一頁0,10
    start = (current_page - 1) * 10
    end = current_page * 10
    type_list = models.UserType.objects.all()[start:end]
    #將全部的頁碼顯示在頁面上
    total_item = models.UserType.objects.all().count()
    a,b = divmod(total_item, 10)
    if b == 0:
        pass
    else:
        a = a + 1
    list_page = []
    if current_page <= 1:
        prev = "<a href='javascript:void(0);'>上一頁</a>"
    else:
        prev = "<a href='/page?p=%s'>上一頁</a>" % (current_page-1,)
    list_page.append(prev)
    for i in range(1,a+1):
        if i == current_page:
            temp = "<a class='active' href='/page?p=%s'>第%s頁</a>" % (i, i,)
        else:
            temp = "<a href='/page?p=%s'>第%s頁</a>" % (i,i,)
        list_page.append(temp)
    str_page = ''.join(list_page)
    from django.utils.safestring import mark_safe
    str_page = mark_safe(str_page)
    return render(request, 'page.html', {'type_list':type_list, 'str_page': str_page})
views.py

詳見武sir博客:http://www.cnblogs.com/wupeiqi/articles/5246483.html

相關文章
相關標籤/搜索