ORM:Object Relational Mapping(關係對象映射)程序員
類名對應------》數據庫中的表名數據庫
類實例對應---------》數據庫表裏的一行數據django
類屬性對應---------》數據庫裏的字段app
obj.id obj.name.....類實例對象的屬性ide
class UserInfo(models.Model): """ 用戶表 """ username = models.CharField(verbose_name='用戶名', max_length=32)
class Department(models.Model): """ 部門表 """ title = models.CharField(verbose_name='標題',max_length=32) class UserInfo(models.Model): """ 用戶表 """ username = models.CharField(verbose_name='用戶名', max_length=32) depart = models.ForeignKey(verbose_name='所屬部門',to="Department")
on_delete: models.CASCADE,刪除部門,則將改部門下的員工所有刪除。 + 代碼判斷 models.DO_NOTHING,刪除部門,引起錯誤IntegrityError models.PROTECT,刪除部門,引起錯誤ProtectedError models.SET_NULL,刪除部門,則將改部門下的員工所屬部門ID設置爲空。(將FK字段設置爲null=True) models.SET_DEFAULT,刪除部門,則將改部門下的員工所屬部門ID設置默認值。(將FK字段設置爲default=2) models.SET,刪除部門,則將執行set對應的函數,函數的返回值就是要給改部門下員工設置的新的部門ID。 例如: def func(): models.Users....... return 10 class MyModel(models.Model): user = models.ForeignKey(to="User",to_field="id"on_delete=models.SET(func),) 方法: models.CASCADE, 刪除邏輯時,經過代碼判斷當前 「部門」 下是否有用戶。 models.SET_NULL,穩妥。 溝通以後在肯定。
depart = models.ForeignKey(verbose_name='所屬部門',to="Department",db_constraint=False) # 無約束,但可使用django orm的連表查詢。 models.UserInfo.objects.filter(depart__title='xxx')
示例1: from django.db import models class Department(models.Model): """ 部門表 ID 名稱 1 教質部 2 Python學院 """ title = models.CharField(verbose_name='標題',max_length=32) class User(models.Model): """ 員工表 ID name depart_id 1 小雪 1 2 冰冰 1 3 小雨 1 4 太亮 2 5 金菊 2 """ name = models.CharField(verbose_name='員工名稱',max_length=32) depart = models.ForeignKey(to='Department') class ClassList(models.Model): """ 班級表 """ title = models.CharField(verbose_name='班級名稱', max_length=32) bzr = models.ForeignKey(to=User,limit_choices_to={'id__lt':4}) teacher = models.ForeignKey(to=User,limit_choices_to={'id__gte':4}) 示例2: from django.db import models class Department(models.Model): """ 部門表 ID 名稱 1 教質部 2 Python學院 """ title = models.CharField(verbose_name='標題',max_length=32) class User(models.Model): """ 員工表 ID name depart_id 1 小雪 1 2 太亮 2 3 小雨 1 4 冰冰 1 5 金菊 2 """ name = models.CharField(verbose_name='員工名稱',max_length=32) depart = models.ForeignKey(to='Department') class ClassList(models.Model): """ 班級表 """ title = models.CharField(verbose_name='班級名稱', max_length=32) bzr = models.ForeignKey(to=User,limit_choices_to={'depart__title':'教質部','id__gt':9}) teacher = models.ForeignKey(to=User,limit_choices_to={'depart__title':'Python學院'})
反向查找的字段。 示例: from django.db import models class Department(models.Model): """ 部門表 ID 名稱 1 教質部 2 Python學院 """ title = models.CharField(verbose_name='標題',max_length=32) class User(models.Model): """ 員工表 ID name depart_id 1 小雪 1 2 太亮 2 3 小雨 1 4 冰冰 1 5 金菊 2 """ name = models.CharField(verbose_name='員工名稱',max_length=32) depart = models.ForeignKey(to='Department') class ClassList(models.Model): """ 班級表 """ title = models.CharField(verbose_name='班級名稱', max_length=32) bzr = models.ForeignKey(to=User,related_name='x') teacher = models.ForeignKey(to=User,related_name='y') from app01 import models # 找班主任小雪帶的全部班級 obj = models.User.objects.filter(name='小雪').first() class_list = obj.x.all() for row in class_list: print(row.title) # 找老師金鑫帶的全部班級 obj1 = models.User.objects.filter(name='金鑫').first() class_list = obj1.y.all() for row in class_list: print(row.title)
對於ForeignKey,通常公司數據量和訪問量不大時,建立FK作約束。數據量和訪問量巨大時,犧牲硬盤空間和程序員代碼量,依次來提供用戶訪問速度。(連表查詢速度會比單表查詢速度慢)函數
class Boy(models.Model): name = models.CharField(max_length=32) class Girl(models.Model): name = models.CharField(max_length=32) boy = models.ManyToManyField('Boy')
class Boy(models.Model): name = models.CharField(max_length=32) class Girl(models.Model): name = models.CharField(max_length=32) class Boy2Girl(models.Model): b = models.ForeignKey(to='Boy') g = models.ForeignKey(to='Girl') class Meta: unique_together = ( ("b", "g"), )
class UserInfo(models.Model): """ 1 好虛 2 戴綠 """ username = models.CharField(verbose_name='標題',max_length=32) class Blog(Model.Model): """ 1 好虛371 1 """ title = models.CharField(verbose_name='標題',max_length=32) a = models.OneToOneField(to='A') 應用場景: class userinfo: """ 老男孩全部員工 (130) """ name = 用戶名 email = 郵箱 ... class Admin: """ 給30我的開帳號(30),能夠登陸教務系統 """ username = 登陸用戶名 password ='密碼' user = o2o(userinfo)
例如:性別的數量不會隨着時間的推移而發生個數的變化。 # 不推薦 class Gender(models.Model): title = models.CharField(max_length=32) class Customer(models.Model): name = models.CharField(verbose_name='姓名',max_length=32) gender = models.ForeignKey(to='Gender') # 推薦 class Customer(models.Model): name = models.CharField(verbose_name='姓名',max_length=32) gender_choices = ( (1,'男'), (2,'女'), ) gender = models.IntegerField(choices=gender_choices) 數據庫優化手段,將固定數據放入內存代替放入數據庫。
class Department(models.Model): title = models.CharField(verbose_name='標題',max_length=32) class UserInfo(models.Model): name = models.CharField(verbose_name='員工名稱',max_length=32) depart = models.ForeignKey(to='Department') roles = models.ManyToManyField(to="Role") class Role(models.Model): title = models.CharField(verbose_name='標題',max_length=32) 增長: models.Department.objects.create(title='銷售部') models.Department.objects.create(**{'title':'銷售部'}) models.UserInfo.objects.create(name='劉也',depart=models.Department.objects.get(id=1)) models.UserInfo.objects.create(name='劉也',depart_id=1) obj = models.UserInfo.objects.filter(name='劉也').first() obj.roles.add([1,2,3]) 刪除: .delete() 修改: models.UserInfo.objects.filter(id__gt=5).update(name='xx') obj = models.UserInfo.objects.filter(name='劉也').first() obj.roles.set([2,3,6,7]) 查詢: models.UserInfo.objects.all() models.UserInfo.objects.values('id','name') models.UserInfo.objects.values_list('id','name')
- 排序 - 連表 - filter篩選條件 __gt __gte __lt __contains __in ...
F Q only # Queryset[obj,obj,obj] modes.UserInfo.objects.all().only('id','name') # select id,name from userinfo # Queryset[{},{},{}] modes.UserInfo.objects.all().values('id','name') # select id,name from userinfo # Queryset[(),(),()] modes.UserInfo.objects.all().values_list('id','name') # select id,name from userinfo 錯錯錯: result = modes.UserInfo.objects.all().only('id','name') for obj in result: print(obj.id,obj.name,obj.age) defer # Queryset[obj,obj,obj] modes.UserInfo.objects.all().defer('name') # select id,age from userinfo select_related 幫助開發者進行主動連表查詢。 # SELECT "app01_user"."id", "app01_user"."name", "app01_user"."depart_id" FROM "app01_user" result = models.User.objects.all() # SELECT "app01_user"."id", "app01_user"."name", "app01_user"."depart_id", "app01_department"."id", "app01_department"."title" FROM "app01_user" INNER JOIN "app01_department" ON ("app01_user"."depart_id" = "app01_department"."id") result = models.User.objects.all().select_related('depart') 注意:若是之後想要獲取部門名稱(跨表),必定要使用select_related進行主動跨表,這樣在最開始獲取數據時,將當前表和關聯表的全部數據都獲取到。 切記:錯錯錯 result = models.User.objects.all() for row in result: print(row.name,row.depart_id,row.depart.title) # row.depart.title就會讓性能大大下降 prefetch_related # 先執行SQL: select * from user where id<100 # 在執行SQL: select * from depart where id in [11,20] result = models.User.objects.filter(id__lt=100).prefetch_related('depart') 對比: 方式一: result = models.User.objects.all() # 1次單表 for row in result: print(row.id,row.name,row.depart.title) # 100次單表 方式二(小於4張表的連表操做): *** result = models.User.objects.all().select_related('depart') # 1次連表查詢 for row in result: print(row.id,row.name,row.depart.title) 方式三(大於4張表連表操做): # 先執行SQL: select * from user; # 在執行SQL: select * from depart where id in [11,20] result = models.User.objects.all().prefetch_related('depart') # 2次單表查詢 for row in result: print(row.id,row.name,row.depart.title) 執行原生SQL,場景:複雜SQL語句 from django.db import connection, connections # cursor = connections['db1'].cursor() cursor = connection.cursor() cursor.execute("""SELECT * from auth_user where id = %s""", [1,]) # row = cursor.fetchall() # 獲取符合條件的全部數據,models.User.objects.all() row = cursor.fetchone() # 獲取符合條件的第一條數據,models.User.objects.all().first()
################################################################## # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET # ################################################################## def all(self) # 獲取全部的數據對象 def filter(self, *args, **kwargs) # 條件查詢 # 條件能夠是:參數,字典,Q def exclude(self, *args, **kwargs) # 條件查詢 # 條件能夠是:參數,字典,Q def select_related(self, *fields) 性能相關:表之間進行join連表操做,一次性獲取關聯的數據。 model.tb.objects.all().select_related() model.tb.objects.all().select_related('外鍵字段') model.tb.objects.all().select_related('外鍵字段__外鍵字段') def prefetch_related(self, *lookups) 性能相關:多表連表操做時速度會慢,使用其執行屢次SQL查詢在Python代碼中實現連表操做。 # 獲取全部用戶表 # 獲取用戶類型表where id in (用戶表中的查到的全部用戶ID) models.UserInfo.objects.prefetch_related('外鍵字段') from django.db.models import Count, Case, When, IntegerField Article.objects.annotate( numviews=Count(Case( When(readership__what_time__lt=treshold, then=1), output_field=CharField(), )) ) students = Student.objects.all().annotate(num_excused_absences=models.Sum( models.Case( models.When(absence__type='Excused', then=1), default=0, output_field=models.IntegerField() ))) def annotate(self, *args, **kwargs) # 用於實現聚合group by查詢 from django.db.models import Count, Avg, Max, Min, Sum v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id')) # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id')).filter(uid__gt=1) # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1 v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id',distinct=True)).filter(uid__gt=1) # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1 def distinct(self, *field_names) # 用於distinct去重 models.UserInfo.objects.values('nid').distinct() # select distinct nid from userinfo 注:只有在PostgreSQL中才能使用distinct進行去重 def order_by(self, *field_names) # 用於排序 models.UserInfo.objects.all().order_by('-id','age') def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None) # 構造額外的查詢條件或者映射,如:子查詢 UserInfo.objects.extra(where=['headline ? %s'], params=['Lennon']) # select * from userinfo where headline > 'Lennon' UserInfo.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"]) # select * from userinfo where (foo='a' OR bar = 'a') and baz = 'a' UserInfo.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,)) """ select id, name, (select col from sometable where othercol > 1) as new_id """ UserInfo.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid']) def reverse(self): # 倒序 models.UserInfo.objects.all().order_by('-nid').reverse() # 注:若是存在order_by,reverse則是倒序,若是多個排序則一一倒序 def defer(self, *fields): models.UserInfo.objects.defer('username','id') 或 models.UserInfo.objects.filter(...).defer('username','id') #映射中排除某列數據 def only(self, *fields): #僅取某個表中的數據 models.UserInfo.objects.only('username','id') 或 models.UserInfo.objects.filter(...).only('username','id') def using(self, alias): 指定使用的數據庫,參數爲別名(setting中的設置) models.UserInfo.objects.filter(id=5).using('db1') ################################################## # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # ################################################## def raw(self, raw_query, params=None, translations=None, using=None): # 執行原生SQL models.UserInfo.objects.raw('select * from userinfo where id > 10 ') # 若是SQL是其餘表時,必須將名字設置爲當前UserInfo對象的主鍵列名 models.UserInfo.objects.raw('select id as nid from 其餘表') # 爲原生SQL設置參數 models.UserInfo.objects.raw('select id as nid from userinfo where nid>%s', params=[12,]) # 將獲取的到列名轉換爲指定列名 name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'} Person.objects.raw('SELECT * FROM some_other_table', translations=name_map) # 指定數據庫 models.UserInfo.objects.raw('select * from userinfo', using="default") ################### 原生SQL ################### from django.db import connection, connections cursor = connection.cursor() # cursor = connections['default'].cursor() cursor.execute("""SELECT * from auth_user where id = %s""", [1]) row = cursor.fetchone() # fetchall()/fetchmany(..) def values(self, *fields): # 獲取每行數據爲字典格式 def values_list(self, *fields, **kwargs): # 獲取每行數據爲元祖 def dates(self, field_name, kind, order='ASC'): # 根據時間進行某一部分進行去重查找並截取指定內容 # kind只能是:"year"(年), "month"(年-月), "day"(年-月-日) # order只能是:"ASC" "DESC" # 並獲取轉換後的時間 - year : 年-01-01 - month: 年-月-01 - day : 年-月-日 models.DatePlus.objects.dates('ctime','day','DESC') def datetimes(self, field_name, kind, order='ASC', tzinfo=None): # 根據時間進行某一部分進行去重查找並截取指定內容,將時間轉換爲指定時區時間 # kind只能是 "year", "month", "day", "hour", "minute", "second" # order只能是:"ASC" "DESC" # tzinfo時區對象 models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.UTC) models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.timezone('Asia/Shanghai')) """ pip3 install pytz import pytz pytz.all_timezones pytz.timezone(‘Asia/Shanghai’) """ def none(self): # 空QuerySet對象 #################################### # METHODS THAT DO DATABASE QUERIES # #################################### def aggregate(self, *args, **kwargs): # 聚合函數,獲取字典類型聚合結果 from django.db.models import Count, Avg, Max, Min, Sum result = models.UserInfo.objects.aggregate(k=Count('u_id', distinct=True), n=Count('nid')) ===> {'k': 3, 'n': 4} def count(self): # 獲取個數 def get(self, *args, **kwargs): # 獲取單個對象 def create(self, **kwargs): # 建立對象 def bulk_create(self, objs, batch_size=None): # 批量插入 # batch_size表示一次插入的個數 objs = [ models.DDD(name='r11'), models.DDD(name='r22') ] models.DDD.objects.bulk_create(objs, 10) def get_or_create(self, defaults=None, **kwargs): # 若是存在,則獲取,不然,建立 # defaults 指定建立時,其餘字段的值 obj, created = models.UserInfo.objects.get_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 2}) def update_or_create(self, defaults=None, **kwargs): # 若是存在,則更新,不然,建立 # defaults 指定建立時或更新時的其餘字段 obj, created = models.UserInfo.objects.update_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 1}) def first(self): # 獲取第一個 def last(self): # 獲取最後一個 def in_bulk(self, id_list=None): # 根據主鍵ID進行查找 id_list = [11,21,31] models.DDD.objects.in_bulk(id_list) models.User.objects.filter(id__in=[11,21,31]) def delete(self): # 刪除 def update(self, **kwargs): # 更新 def exists(self): # 是否有結果