一 模型層經常使用字段和參數html
1.模型表創建經常使用字段git
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
1. AutoField:int自增主鍵列。必須填入參數 primary_key=True。當model中若是沒有自增列,則自動會建立一個列名爲id的列 id = models.AutoField(primary_key=True) 2.CharField:字符串,至關於varchar。必須提供max_length參數,不能超過255。 title = models.CharField(max_length=255) 3.IntegerField:整數類型,範圍在 -2147483648 to 2147483647。(通常不用它來存手機號(位數也不夠),直接用字符串存,) kucun = models.IntegerField(null=True) # null參數可不填 4.DecimalField:浮點類型。參數1 max_digits表示總共的位數,參數2 decimal_places表示小數的位數 price = models.DecimalField(max_digits=8,decimal_places=2) 5.DateField: create_time = models.DateField() # 不指定auto_now或auto_now_add時,須要本身傳參數 關鍵性的參數: 1.auto_now:每次操做數據 都會自動刷新當前操做的時間 2.auto_now_add:在建立數據的時候 會自動將建立時間記錄下來 後續的修改不會影響該字段
補充:sql
1. BooleanField 例:給該字段傳值的時候 你只須要傳佈爾值便可,可是對應到數據庫 它存的是0和1。 is_delete = BooleanField() 2. TextField:文本類型,用來存大段文本。 3. FileField: 字符串,路徑保存在數據庫,文件上傳到指定目錄 參數: 1.upload_to = "" 用戶上傳的文件會自動放到等號後面指定的文件路徑中 2.storage = None 存儲組件,默認django.core.files.storage.FileSystemStorage
自定義字段:數據庫
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
""" django雖然沒有給你提供定義char字段的方法 可是給你暴露一個接口 用戶能夠自定義char字段 """ class MyChar(models.Field): def __init__(self, max_length, *args, **kwargs): self.max_length = max_length super().__init__(max_length=max_length, *args, **kwargs) def db_type(self, connection): return 'char(%s)' % self.max_length
2.字段參數django
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
null 用於表示某個字段能夠爲空。 unique 若是設置爲unique=True 則該字段在此表中必須是惟一的 。 db_index 若是db_index=True 則表明着爲此字段設置索引。 default 爲該字段設置默認值。
3.表與表之間的關係字段app
https://www.cnblogs.com/tfzz/p/11537119.htmlide
4.choices字段補充url
1.語法: # 設置對應值 字段名1 =((數字1,對應值1),(數字2,對應值2),...) # 也能夠是列表套元組 # 綁定關係 字段名2 = models.字段類型(choices = 字段名1) # 查詢 對象。get_字段名2_display() 2.示例:
class User(models.Model):
username = models.CharField(max_length=32)
age = models.IntegerField()
genser_choices = (
(1,'男'),(2,'女'),(3,'其餘')
)
gender = models.IntegerField(choices=genser_choices)
"""
1 存choice裏面羅列的數字與中文對應關係
print(user_obj.get_gender_display())
只要是choices字段 在獲取數字對應的註釋 固定語法
get_choices字段名_display()
2 存沒有羅列遲來的數字
不會報錯 仍是展現數字
"""
user_obj = models.User.objects.filter(pk=1).first()
print(user_obj.get_gender_display()) # 男
"""
只要是choices字段 在獲取數字對應的註釋 固定語法
get_choices字段名_display()
"""
二 設置Django打印sql語句es5
在settings.py文件中粘貼便可spa
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level':'DEBUG', }, } }
三 單表雙下滑線查詢(至關於新的過濾條件)
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
1.大於:__gt 小於:__lt 大於等於:__gte 小於等於:__lte #價格 大於 小於 大於等於 小於等於 filter(price__gt='90') filter(price__lt='90') filter(price_gte='90') filter(price_lte='90') 2.__in:存在與某幾個條件中(至關於或的關係) filter(price__in=['11','22','33']) models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in 3. __range 在某個範圍內(顧頭又顧尾) filter(price__range=[50,90]) 4. __contains模糊查詢 models.Tb1.objects.filter(name__contains="ven") # 獲取name字段包含"ven"的,區分大小寫 models.Tb1.objects.filter(name__icontains="ven") # icontains大小寫不區分 5.__startswith,__istartswith以什麼開頭(區分大小寫和不區分) 6.__endswith, __iendswith以什麼結尾(區分大小寫和不區分) 7.date字段能夠經過在其後加__year,__month,__day等來獲取date的特色部分數據 filter(create_time__year='2017') # 查詢2017年的數據
四 多表操做
1.一對多關係 :一對多字段的增刪改查
以(Book表 和出版社Publish表爲例,一對多關係,爲publish外鍵)爲例:
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
from django.db import models class Book(models.Model): title = models.CharField(max_length=255) price = models.DecimalField(max_digits=8,decimal_places=2) publish_date = models.DateField(auto_now_add=True) # 庫存數 kucun = models.IntegerField(null=True) # 賣出數 maichu = models.IntegerField(null=True) publish = models.ForeignKey(to='Publish') # 默認是跟publish的主鍵字段作的一對多外鍵關聯 authors = models.ManyToManyField(to='Author') # 虛擬字段 1.自動建立第三張表 2.幫助orm跨表查詢 def __str__(self): return self.title class Publish(models.Model): name = models.CharField(max_length=32) addr = models.CharField(max_length=32) # email = models.EmailField() # 就是varchar(254) def __str__(self): return self.name
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
1.增: 針對外鍵關聯的字段 兩種添加方式 第一種經過 外鍵字段_id=值 models.Book.objects.create(title='三國演義',price=189.99,publish_id=1) 第二種經過 外鍵字段=對象 publish_obj = models.Publish.objects.filter(pk=2).first() models.Book.objects.create(title='紅樓夢',price=999.99,publish=publish_obj) 2.刪 models.Publish.objects.filter(pk=2).delete() # 默認都是級聯更新 級聯刪除 3.改 第一種經過 外鍵字段_id=值 models.Book.objects.filter(pk=1).update(publish_id=3) 第二種經過 外鍵字段=對象 publish_obj = models.Publish.objects.filter(pk=2).first() models.Book.objects.filter(pk=1).update(publish=publish_obj) 4.查 .filter() .all()
2.多對多關係:多對多字段的 增刪改查
以(Book表 和做者Author表爲例,多對多關係authors爲外鍵)爲例:
注意:對象點擊多對多虛擬字段 會直接跨到多對多的第三張表
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=255) price = models.DecimalField(max_digits=8,decimal_places=2) publish_date = models.DateField(auto_now_add=True) # 庫存數 kucun = models.IntegerField(null=True) # 賣出數 maichu = models.IntegerField(null=True) publish = models.ForeignKey(to='Publish') # 默認是跟publish的主鍵字段作的一對多外鍵關聯 authors = models.ManyToManyField(to='Author') # 虛擬字段 1.自動建立第三張表 2.幫助orm跨表查詢 def __str__(self): return self.title class Author(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() author_detail = models.OneToOneField(to='AuthorDetail')
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
1.增:add能夠傳做者id數字,也能夠直接傳做者對象,而且支持傳多個位置參數(不要混着用) book_obj = models.Book.objects.filter(pk=1).first() book_obj.authors.add(1) book_obj.authors.add(2,3) author_obj = models.Author.objects.filter(pk=1).first() author_obj1 = models.Author.objects.filter(pk=2).first() author_obj2 = models.Author.objects.filter(pk=3).first() book_obj.authors.add(author_obj) book_obj.authors.add(author_obj1,author_obj2) 2.刪:remove()括號內既能夠傳數字 也能夠傳對象 ,而且支持傳對個 逗號隔開便可 book_obj = models.Book.objects.filter(pk=1).first() book_obj.authors.remove(3) book_obj.authors.remove(1,2) author_obj = models.Author.objects.filter(pk=1).first() author_obj1 = models.Author.objects.filter(pk=2).first() author_obj2 = models.Author.objects.filter(pk=3).first() book_obj.authors.remove(author_obj) book_obj.authors.remove(author_obj1,author_obj2) 3.改:set()括號內 須要傳一個可迭代對象 ,可迭代對象中 能夠是多個數字組合,也能夠是多個對象組合,可是不要混着用!!! # 將主鍵爲1的書籍對象 做者修改成2,3 book_obj = models.Book.objects.filter(pk=1).first() book_obj.authors.set([2,]) book_obj.authors.set([2,3]) # author_obj = models.Author.objects.filter(pk=1).first() # author_obj1 = models.Author.objects.filter(pk=2).first() # author_obj2 = models.Author.objects.filter(pk=3).first() # book_obj.authors.set([author_obj,]) # book_obj.authors.set([author_obj, author_obj1, author_obj2]) 4.查 # 將某本書跟做者的關係所有清空 # book_obj = models.Book.objects.filter(pk=1).first() # book_obj.authors.clear() # 清空當前書籍與做者的全部關係 5.總結: """ add() set() remove() 上面三個都支持傳數字 或者對象 而且能夠傳多個 可是set須要傳可迭代對象 clear() clear括號內不須要傳任何參數 """
3.正向和反向跨表查詢
正向查詢:當前表中存在着另外一張要查詢表的外鍵,能夠經過 .外鍵 跨表查詢稱之爲正向查詢。
反向查詢:當前表中不存在着另外一張要查詢表的外鍵,能夠經過 .另外一張表名 跨查詢稱之爲反向查詢。
示例表
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=255) price = models.DecimalField(max_digits=8,decimal_places=2) publish_date = models.DateField(auto_now_add=True) # 庫存數 kucun = models.IntegerField(null=True) # 賣出數 maichu = models.IntegerField(null=True) publish = models.ForeignKey(to='Publish') # 默認是跟publish的主鍵字段作的一對多外鍵關聯 authors = models.ManyToManyField(to='Author') # 虛擬字段 1.自動建立第三張表 2.幫助orm跨表查詢 def __str__(self): return self.title class Publish(models.Model): name = models.CharField(max_length=32) addr = models.CharField(max_length=32) # email = models.EmailField() # 就是varchar(254) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() author_detail = models.OneToOneField(to='AuthorDetail') def __str__(self): return self.name class AuthorDetail(models.Model): phone = models.BigIntegerField() addr = models.CharField(max_length=64) """ models.py中的模型類__str__方法 必須返回一個字符串形式數據!!! """ def __str__(self): return self.addr
#基於對象的正反向查詢
正向: 對象.關聯字段(外鍵).字段 /all()
反向: 對象.表名小寫(_set).字段/all()
要點:先拿到對象,再經過對象去查對應的外鍵字段,分兩步
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
正向查詢 1.查詢書籍id是1 的出版社名稱(一對多) 書籍---->出版社 book_obj = models.Book.objects.filter(pk=1).first() print(book_obj.publish.name) # 對象點外鍵字段直接跨到另外一張表中 print(book_obj.publish.addr) 2.查詢書籍id是2 的做者姓名(多對多) 書籍———》做者 book_obj = models.Book.objects.filter(pk=2).first() print(book_obj.authors) # app01.Author.None print(book_obj.authors.all()) res = book_obj.authors.all() for r in res: print(r.name) 反向查詢 1.查詢出版社是東方出版社出版的書籍(一對多) 出版社———》書籍 publish_obj = models.Publish.objects.filter(name='東方出版社').first() # print(publish_obj.book_set) # app01.Book.None print(publish_obj.book_set.all()) 6.查詢電話號碼是130的做者姓名 (一對一) 信息表———》做者 author_detail_obj = models.AuthorDetail.objects.filter(phone=130).first() print(author_detail_obj.author.name) print(author_detail_obj.author.age) #正向和反向查詢時結果可能爲多個時加上 .all(),反向還要表名小寫:表名小寫_set.all()
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
# 5.查詢做者是jason的寫過的全部的書籍(多對多) 做者———》 書 # author_obj = models.Author.objects.filter(name='jason').first() # print(author_obj.book_set) # app01.Book.None # print(author_obj.book_set.all())
#基於雙下換線的正反向查詢
正向:按字段,跨表能夠在filter,也能夠在values中
反向:按表名小寫,跨表能夠在filter,也能夠在values中
正向:關聯字段(外鍵)__字段
反向:表名小寫__字段
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
1.查詢jason做者的手機號(一對一) 做者——》信息 正向: res=models.Author.objects.filter(name='jason').values('author_detail__phone','author_detail__addr') print(res) 反向: res1 = models.AuthorDetail.objects.filter(author__name='jason').values('phone') print(res1) 查詢jason這個做者的年齡和手機號 (一對一) 做者——》信息 正向: res=models.Author.objects.filter(name='jason').values('age','author_detail__phone') # 年齡在本表中不須要跨表,手機號不在須要跨表 print(res) 反向: res1=models.AuthorDetail.objects.filter(author__name='jason').values('phone','author__age') # 手機號在本表中不須要跨表,年齡不在須要跨表 print(res1) 2.查詢手機號是130的做者年齡(一對一) 正向: res = models.AuthorDetail.objects.filter(phone=130).values('author__age') print(res) 反向: res1 = models.Author.objects.filter(author_detail__phone=130).values('age') print(res1) 3.查詢書籍id是1 的做者的電話號碼 res=models.Book.objects.filter(pk=1).values('authors__author_detail__phone') # res1 = models.Book.objects.filter(pk=1).values('外鍵字段1__外鍵字段2__外鍵字段3__普通字段') print(res) """只要表裏面有外鍵字段 你就能夠無限制跨多張表""" 4. # 1.查詢出版社爲北方出版社的全部圖書的名字和價格 # res = models.Publish.objects.filter(name='北方出版社').values('book__title','book__price') # print(res) # 2.查詢北方出版社出版的價格大於19的書 # res = models.Book.objects.filter(price__gt=19,publish__name='北方出版社').values('title','publish__name') # print(res)
4.聚合查詢(aggregate)
from django.db.models import Max,Min,Count,Avg,Sum res = models.Book.objects.aggregate(Sum('price')) res1 = models.Book.objects.aggregate(Avg('price')) res2 = models.Book.objects.aggregate(Count('price')) res3 = models.Book.objects.aggregate(Max('price')) res4 = models.Book.objects.aggregate(Min('price')) res5=models.Book.objects.aggregate(Max('price'),Min('price'),Count('pk'),Avg('price'),Sum('price')) print(res5) print(res) print(res1) print(res2)
5.分組
# 分組查詢 # 統計每一本書的做者個數 from django.db.models import Max, Min, Count, Avg, Sum # res = models.Book.objects.annotate(author_num = Count('authors')).values('author_num','title') # 依據Book分組,author_num爲別名 # print(res) # 統計出每一個出版社賣的最便宜的書的價格 # res = models.Publish.objects.annotate(mmp = Min('book__price')).values('name','mmp') # print(res) # 統計不止一個做者的圖書 # res = models.Book.objects.annotate(author_num=Count('authors')).filter(author_num__gt=1) # print(res) """ 只要是queryset對象 就能夠無限制的調用queryset對象的方法!!! 最最經常使用的就是對一個已經filter過濾完的數據 再進行更細化的篩選 """ # 查詢各個做者出的書的總價格 # res = models.Author.objects.annotate(sp=Sum('book__price')).values('name','sp') # print(res)
6.F查詢(獲取字段的值)
#F查詢的本質就是從數據庫中獲取某個字段的值 # 查詢庫存數大於賣出數的書籍 """以前查詢等號後面的條件都是咱們認爲輸入的 如今變成了須要從數據庫中獲取數據放在等號後面 """ from django.db.models import F res = models.Book.objects.filter(kucun__gt=F('maichu')) print(res)
# 將書籍庫存數所有增長1000
# models.Book.objects.update(kucun=F('kucun')+1000)
# 把全部書名後面加上'新款'
# from django.db.models.functions import Concat
# from django.db.models import Value
#
# ret3 = models.Book.objects.update(title=Concat(F('title'), Value('新款')))
# models.Book.objects.update(title = F('title')+'新款') # 不能這麼寫
7.Q查詢(更改條件之間的關係)
# Q查詢 from django.db.models import Q # 查詢書籍名稱是三國演義或者價格是444.44 # res = models.Book.objects.filter(title='三國演義',price=444.44) # filter只支持and關係 # res1 = models.Book.objects.filter(Q(title='三國演義'),Q(price=444)) # 若是用逗號 那麼仍是and關係 # res2 = models.Book.objects.filter(Q(title='三國演義')|Q(price=444)) # 或的關係 # res3 = models.Book.objects.filter(~Q(title='三國演義')|Q(price=444)) # ~非的關係 # print(res2) # Q高級用法 q = Q() q.connector = 'or' # 修改查詢條件的關係 默認是and q.children.append(('title__contains','三國演義')) # 往列表中添加篩選條件 q.children.append(('price__gt',444)) # 往列表中添加篩選條件 res = models.Book.objects.filter(q) # filter支持你直接傳q對象 可是默認仍是and關係 print(res)