Django框架(十二)—— 補充:inclusion_tag、defer、only、choice、事務、建立多對多的第三張表
阿新 • • 發佈:2018-11-25
補充:inclusion_tag、defer、only、choice、事務、建立多對多的第三張表
一、inclusion_tag
1、作用
用於生成HTML片段,是資料由引數傳入而變成動態
2、使用
# 1.app下新建一個模組,templatetags # 2.建立一個py檔案(mytag.py) # 3.匯入Library模組,例項化 from django.template import Library register=Library() # -----> register名字一定不能變 # 4.寫裝飾器(標籤,過濾器,inclusion_tag) @inclusion_tag('模板路徑',name='重新命名') def my_in(): # 不寫,寫多個,不寫不傳,寫多個,按空格來傳參 # 一堆邏輯處理,查資料庫 ret=Book.object.all() return {''books':ret} # 在模板中: 可以用books這個變數,渲染頁面 # 5.應用: -在另一個模板中: -{%load mytag.py%} -{% my_in %}
二、defer與only
1、定義
defer ----> 除了指定欄位之外
only ----> 只查詢幾個欄位
2、使用
ret=Book.object.all().only('name')
# 等價於,id始終都會查
ret=Book.object.all().only('id','name')
3、注意點
ret=models.Author.objects.only('nid')
for i in ret:
# 查詢的name不在的ret中,會再次查詢資料庫,造成資料庫壓力大
print(i.name)
三、事務
1、原子性操作
2、語法
from django.db import transition
with transition.atomic():
sql1
sql2
四、choice
1、定義
模型表中某個欄位,可以指定choice,用在選擇不經常變的情況,經常變,儘量用資料庫
2、使用
# db_constraint 是否在資料庫中建立外來鍵約束,預設為True user_type=models.ForeignKey(to='Info', to_field='id',db_constraint=False) #取出對應的漢字 # author物件.user_type.name mychoice=((1,'男'),(2,'女'),(3,'其他')) # dd = models.ForeignKey(to='Info', to_field='id') #取出對應的漢字 dd = models.ForeignKey(choices=mychoice)
五、多對多建立第三張表
1、多對多的操作
https://www.cnblogs.com/linagcheng/p/9953252.html
2、三種方法建立第三張表
(1)手動建立第三張表(不建立關聯關係)
# 手動建立第三張表(不建立關聯關係)
class Book(models.Model):
# 預設會建立id
name = models.CharField(max_length=32)
class Author(models.Model):
name = models.CharField(max_length=32)
class Book2Author(models.Model):
id = models.AutoField(primary_key=True)
book=models.ForeignKey(to='Book',to_field='id')
author=models.ForeignKey(to='Author',to_field='id')
# 不管是插入和查詢,刪除,都很麻煩(一般不用)
(2)自動建立第三張表
# 自動建立第三張表
查詢,插入,刪除,都很方便
缺點:欄位是固定的,第三張表如果要新增欄位,實現不了
(3)手動建立第三張表,建立關聯關係
class Book(models.Model):
# 預設會建立id
name = models.CharField(max_length=32)
# 中介模型,手動指定第三張中間表是
authors=models.ManyToManyField(to='Author',through='Book2Author',through_fields=('book','author'))
class Author(models.Model):
name = models.CharField(max_length=32)
class Book2Author(models.Model):
id = models.AutoField(primary_key=True)
book=models.ForeignKey(to='Book',to_field='id')
author=models.ForeignKey(to='Author',to_field='id')
# through:來指定我的第三張表是哪個
# through_fields:('book','author'),第一個值是:從中間表找到設定關聯欄位的表,通過哪個欄位,第一個位置就寫它
# 終極總結:防止混了:關聯欄位就是表名小寫,第一個值:就是當前表的表名小寫
# 查詢,新增,刪除,都很方便
# 第三張表,可以新增別的欄位