一计技、ORM是什么?
ORM 是 python編程語言后端web框架 Django的核心思想现横,“Object Relational Mapping”椿访,即對象-關系映射乌企,簡稱ORM。
-
一個句話理解就是:創(chuàng)建一個實例對象成玫,用創(chuàng)建它的類名當做數(shù)據(jù)表名加酵,用創(chuàng)建它的類屬性對應數(shù)據(jù)表的字段,當對這個實例對象操作時哭当,能夠?qū)狹ySQL語句
-
看下面例子描述:
class User(父類省略): uid = ('uid', "int unsigned") name = ('username', "varchar(30)") email = ('email', "varchar(30)") password = ('password', "varchar(30)") ...省略... u = User(uid=12345, name='Michael', email='test@orm.org', password='my-pwd') u.save() # 對應如下sql語句 # insert into User (username,email,password,uid) # values ('Michael','test@orm.org','my-pwd',12345)
說明:
- 所謂的ORM就是讓開發(fā)者在操作數(shù)據(jù)庫的時候猪腕,能夠像操作對象時通過xxxx.屬性=yyyy一樣簡單,這是開發(fā)ORM的初衷
- 只不過ORM的實現(xiàn)較為復雜荣病,Django中已經(jīng)實現(xiàn)了 很復雜的操作码撰,本節(jié)知識 主要通過完成一個 insert相類似的ORM,理解其中的道理就就可以了
二个盆、通過元類簡單實現(xiàn)ORM中的insert功能
-
2.1、看下面一個例子
class ModelMetaclass(type): def __new__(cls, name,bases,attrs): mappings = dict() # 判斷是否需要保存 for k,v in attrs.items(): # 判斷是否是指定的 StringField 或者 IntegerField的實例對象 if isinstance(v,tuple): # print('Found mapping: %s ==> %s'%(k,v)) mappings[k] = v # 刪除這些已經(jīng)在字典中的屬性 for k in mappings.keys(): attrs.pop(k) # 將之前的uid/name/email/password 以及對應的對象引用朵栖、類名字 attrs['__mappings__'] = mappings # 保持屬性和列的映射關系 attrs['__table__'] = name # 假設表名和類名一致 return type.__new__(cls,name,bases,attrs) class User(metaclass=ModelMetaclass): uid = ('uid',"int unsigned") name = ('username',"varchar(30)") email = ('email',"varchar(30)") password = ('password',"varchard(30)") # 當指定元類之后颊亮,以上的類屬性將不在類中,而是在__mappings__屬性指定的字典中存儲 # 以上User類中有 # __mappings__ = { # "uid": ('uid', "int unsigned") # "name": ('username', "varchar(30)") # "email": ('email', "varchar(30)") # "password": ('password', "varchar(30)") # } # __table__ = "User" def __init__(self,**kwargs): for name,value in kwargs.items(): setattr(self,name,value) def save(self): field = [] args = [] for k,v in self.__mappings__.items(): field.append(v[0]) args.append(getattr(self,k,None)) sql = 'insert into %s (%s) values (%s)'%(self.__table__,','.join(field),','.join([str(i) for i in args])) print("SQL: %s"%sql) u = User(uid=12345, name='Michael', email='test@orm.org', password='my-pwd') # print(u.__dict__) u.save()
打印結(jié)果如下:
SQL: insert into User (uid,username,email,password) values (12345,Michael,test@orm.org,my-pwd)
提示:從是上面的打印我們可以看到 values后面括號中的value是有問題的陨溅,有些不是int類型终惑,是字符串類型,在執(zhí)行 sql 語句的時候會報錯的门扇,在下面我們把它的類型判斷一下雹有,進行完善
-
2.2、完善對數(shù)據(jù)類型的檢測臼寄,重寫上面的
save()
方法霸奕,如下def save(self): fields = [] args = [] for k, v in self.__mappings__.items(): fields.append(v[0]) args.append(getattr(self, k, None)) args_temp = list() for temp in args: # 判斷入如果是數(shù)字類型 if isinstance(temp, int): args_temp.append(str(temp)) elif isinstance(temp, str): args_temp.append("""'%s'""" % temp) sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(args_temp)) print('SQL: %s' % sql) u = User(uid=12345, name='Michael', email='test@orm.org', password='my-pwd') # print(u.__dict__) u.save()
運行效果入下:
SQL: insert into User (email,uid,password,username) values ('test@orm.org',12345,'my-pwd','Michael')
三、抽取到基類中
-
3.1吉拳、元類的創(chuàng)建
class ModelMetaclass(type): def __new__(cls, name, bases, attrs): mappings = dict() # 判斷是否需要保存 for k, v in attrs.items(): # 判斷是否是指定的StringField或者IntegerField的實例對象 if isinstance(v, tuple): print('Found mapping: %s ==> %s' % (k, v)) mappings[k] = v # 刪除這些已經(jīng)在字典中存儲的屬性 for k in mappings.keys(): attrs.pop(k) # 將之前的uid/name/email/password以及對應的對象引用质帅、類名字 attrs['__mappings__'] = mappings # 保存屬性和列的映射關系 attrs['__table__'] = name # 假設表名和類名一致 return type.__new__(cls, name, bases, attrs)
-
3.2、基類的創(chuàng)建
class Model(object, metaclass=ModelMetaclass): def __init__(self, **kwargs): for name, value in kwargs.items(): setattr(self, name, value) def save(self): fields = [] args = [] for k, v in self.__mappings__.items(): fields.append(v[0]) args.append(getattr(self, k, None)) args_temp = list() for temp in args: # 判斷入如果是數(shù)字類型 if isinstance(temp, int): args_temp.append(str(temp)) elif isinstance(temp, str): args_temp.append("""'%s'""" % temp) sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(args_temp)) print('SQL: %s' % sql)
-
3.3留攒、創(chuàng)建一個類對象煤惩,并保存數(shù)據(jù)
class Person(Model): uid = ('uid', "int unsigned") name = ('username', "varchar(30)") email = ('email', "varchar(30)") password = ('password', "varchar(30)") p = Person(uid=12345, name='Michael', email='test@orm.org', password='my-pwd') # print(p.__dict__) p.save()
-
4.4、上面 4.1炼邀、4.2魄揉、4.3 是連著的,在基類
Model
里面拭宁,我們還可以寫 : 其他的 方法去實現(xiàn) sql 語句的功能洛退,上面只是寫了一個插入的方法票彪,Django框架 里面的底層就是如此實現(xiàn)的。只不過他們是變化了一下寫法不狮,如下:我們寫
uid = ('uid', "int unsigned")
Django 寫
uid = IntergerField("uid")
提示:就上面這一點區(qū)別降铸,要理解上面代碼的ORM思想