当前位置:网站首页>Descriptor implements ORM model
Descriptor implements ORM model
2022-07-06 02:51:00 【chuntian_ tester】
Catalog
1.__set__ Method : Set properties
2.__get__ Method : Access properties
3.__delete__ Method : Delete attribute
4. Descriptor implementation ORM Model :
Cannot trigger when accessing or modifying the properties of the descriptor object __setattr__ Other methods , It will only trigger __set__,__get__,__delete__ Method .
ORM Model : Class name corresponds to table name , The data row corresponding to the object , Class attribute corresponds to each field of the data row , There are several table fields , Just bind several class attributes ; Adding data to the table is creating objects , Every time an object is created , Is to add a row of data records .
ORM Functions of the framework :
1. Establish correspondence between model classes and tables , It allows us to operate the database in an object-oriented way .
2. According to the design of the model class to generate tables in the database .
3. Through convenient configuration, the database can be switched .
MySql Common data types :
1. Integers :int,bit
2. decimal :decimal(decimal Represents a floating point number ,decimal(5,2) Indicates total 5 digit , Decimal share 2 position )
3. character string :varchar( Variable length ),char( Immutable length )
4. Date time :date,time,datetime
5. Enumeration type :enum
Model cases :
"""
django Of ORM The model field
BooleanField: Boolean fields ,True or False
CharField(max_length= Maximum length ): character string , Parameters max_length Represents the maximum number of characters
IntegerField: Integers
"""
class TestReport(BaseTable):
class Meat:
verbose_name = ' Test report '
db_table = "TestReport"
report_name = models.CharField(max_length=40, null=False)
start_at = models.CharField(max_length=40, null=True)
status = models.BooleanField()
testRun = models.IntegerField()
successes = models.IntegerField()
reports = models.TextField()1.__set__ Method : Set properties
"""
As long as a class appears :
__get__(self,instance,owner)
__set__(self,instance,value)
__delete__(self,instance)
__set_name__(self,owner,name)
Any of the methods in , This class is not an ordinary class ,
Should be called :
Descriptor class ( Apply to ORM In the model )
"""
class Field(object):
"""
As long as any of the following methods appear in a class , This class is a descriptor class
"""
def __get__(self, instance, owner):
pass
def __set__(self, instance, value):
print('---set--- Method triggered ')
def __delete__(self, instance):
pass
class Model(object):
attr = Field() # attr Is a descriptor object , Cannot trigger when modifying __setattr__ Other methods ,
# Only those inside the descriptor class can be triggered __set__ Method
if __name__ == '__main__':
m = Model()
m.attr = 666 # Try to modify attr attribute
print(m.attr)
# Output :
---set - -- Method triggered
None
class Field(object):
"""
As long as any of the following methods appear in a class , This class is a descriptor class
"""
def __get__(self, instance, owner):
pass
def __set__(self, instance, value):
"""
:param instance: Modified object
:param value: Modified value
:return:
"""
print('---set--- Method triggered ')
self.value = value
print(self) # <__main__.Field object at 0x7fecc01f8a30>
print(instance) # <__main__.Model object at 0x7fecc01f8a00>
print(value) # 666
def __delete__(self, instance):
pass
class Model(object):
attr = Field() # attr Is a descriptor object , Cannot trigger when modifying __setattr__ Other methods ,
# Only those inside the descriptor class can be triggered __set__ Method
if __name__ == '__main__':
m = Model()
print(m) # <__main__.Model object at 0x7fecc01f8a00>, And instance identical
m.attr = 666 # Try to modify attr attribute
2.__get__ Method : Access properties
"""
As long as a class appears :
__get__(self,instance,owner)
__set__(self,instance,value)
__delete__(self,instance)
__set_name__(self,owner,name)
Any of the methods in , This class is not an ordinary class ,
Should be called :
Descriptor class ( Apply to ORM In the model )
"""
class Field(object):
"""
As long as any of the following methods appear in a class , This class is a descriptor class
"""
def __get__(self, instance, owner):
print('---get--- Method triggered ')
def __set__(self, instance, value):
"""
:param instance: Modified object
:param value: Modified value
:return:
"""
print('---set--- Method triggered ')
self.value = value
def __delete__(self, instance):
pass
class Model(object):
attr = Field() # attr Is a descriptor object , Cannot trigger when modifying __setattr__ Other methods ,
# Only those inside the descriptor class can be triggered __set__ Method
if __name__ == '__main__':
m = Model()
m.attr = 666 # Try to modify attr attribute
print(m.attr)
# Output :
---set - -- Method triggered
---get - -- Method triggered
None
"""
As long as a class appears :
__get__(self,instance,owner)
__set__(self,instance,value)
__delete__(self,instance)
__set_name__(self,owner,name)
Any of the methods in , This class is not an ordinary class ,
Should be called :
Descriptor class ( Apply to ORM In the model )
"""
class Field(object):
"""
As long as any of the following methods appear in a class , This class is a descriptor class
"""
def __get__(self, instance, owner):
print('---get--- Method triggered ')
print(instance) # <__main__.Model object at 0x7f80b81a09d0>
print(owner) # <class '__main__.Model'>
return self.value
def __set__(self, instance, value):
"""
:param instance: Modified object
:param value: Modified value
:return:
"""
print('---set--- Method triggered ')
self.value = value
def __delete__(self, instance):
pass
class Model(object):
attr = Field() # attr Is a descriptor object , Cannot trigger when modifying __setattr__ Other methods ,
# Only those inside the descriptor class can be triggered __set__ Method
if __name__ == '__main__':
m = Model()
m.attr = 666 # Try to modify attr attribute
print(m.attr) # 666
# Output :
---set - -- Method triggered
---get - -- Method triggered
< __main__.Model object at 0x7f80b81a09d0 >
< class '__main__.Model'>
666
3.__delete__ Method : Delete attribute
"""
As long as a class appears :
__get__(self,instance,owner)
__set__(self,instance,value)
__delete__(self,instance)
__set_name__(self,owner,name)
Any of the methods in , This class is not an ordinary class ,
Should be called :
Descriptor class ( Apply to ORM In the model )
"""
class Field(object):
"""
As long as any of the following methods appear in a class , This class is a descriptor class
"""
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
"""
:param instance: Modified object
:param value: Modified value
:return:
"""
print('---set--- Method triggered ')
self.value = value
def __delete__(self, instance):
print('---delete--- Method triggered ')
class Model(object):
attr = Field() # attr Is a descriptor object , Cannot trigger when modifying __setattr__ Other methods ,
# Only those inside the descriptor class can be triggered __set__ Method
if __name__ == '__main__':
m = Model()
m.attr = 666 # Try to modify attr attribute
del m.attr # ---delete--- Method triggered
print(m.attr) # None
# Output :
---set - -- Method triggered
---delete - -- Method triggered
666
"""
As long as a class appears :
__get__(self,instance,owner)
__set__(self,instance,value)
__delete__(self,instance)
__set_name__(self,owner,name)
Any of the methods in , This class is not an ordinary class ,
Should be called :
Descriptor class ( Apply to ORM In the model )
"""
class Field(object):
"""
As long as any of the following methods appear in a class , This class is a descriptor class
"""
def __get__(self, instance, owner):
print('---get--- Method triggered ')
print(instance) # <__main__.Model object at 0x7f80b81a09d0>
print(owner) # <class '__main__.Model'>
return self.value
def __set__(self, instance, value):
"""
:param instance: Modified object
:param value: Modified value
:return:
"""
print('---set--- Method triggered ')
self.value = value
def __delete__(self, instance):
print('---delete--- Method triggered ')
print(instance) # <__main__.Model object at 0x7ff61806a160>
self.value = None
class Model(object):
attr = Field() # attr Is a descriptor object , Cannot trigger when modifying __setattr__ Other methods ,
# Only those inside the descriptor class can be triggered __set__ Method
if __name__ == '__main__':
m = Model()
m.attr = 666 # Try to modify attr attribute
del m.attr # ---delete--- Method triggered
print(m.attr) # None
# Output :
---set - -- Method triggered
---delete - -- Method triggered
< __main__.Model object at 0x7ff61806a160 >
---get - -- Method triggered
< __main__.Model object at 0x7ff61806a160 >
<class '__main__.Model'>
None
4. Descriptor implementation ORM Model :
"""
Through the descriptor ORM Model
"""
class CharField(object):
def __init__(self,max_length=20):
self.max_length = max_length
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
# First, judge whether it is empty
if value is not None:
# Then judge whether it is a string
if isinstance(value, str):
# Then judge whether the length meets the requirements
if len(value) <= self.max_length:
self.value = value
else:
raise TypeError('length need less than {}'.format(self.max_length))
else:
raise TypeError('need a str')
else:
raise TypeError("can not be None")
def __delete__(self, instance):
self.value = None
class IntegerField(object):
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
# First, judge whether it is empty
if value is not None:
# Then judge whether it is an integer int
if isinstance(value, int):
self.value = value
else:
raise TypeError('need a int')
else:
raise TypeError("can not be None")
def __delete__(self, instance):
self.value = None
class UserModel(object):
# Define the model class of user information
name = CharField(max_length=20) # Definition :name Can only be assigned as a string
pwd = CharField(max_length=40)
age = IntegerField() # Definition :age Can only be assigned as an integer
if __name__ == '__main__':
user = UserModel()
user.name = " Springfield "
print(user.name) # Output : Springfield
user.age = 130
print(user.age) # Output : 130
user.pwd = 'wsdgdgdrgerdsfs Way van der Sar sends Arthur fisaffa sfa fda fsdf sdf fg'
print(user.pwd) # Output : TypeError: length need less than 40
边栏推荐
- Shell script updates stored procedure to database
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 21
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 8
- Redis skip table
- Classic interview question [gem pirate]
- 【若依(ruoyi)】设置主题样式
- 2.13 simulation summary
- Pat 1084 broken keyboard (20 points) string find
- [network security interview question] - how to penetrate the test file directory through
- How to improve the enthusiasm of consumers when the member points marketing system is operated?
猜你喜欢

codeforces每日5题(均1700)-第六天

故障分析 | MySQL 耗尽主机内存一例分析

Li Kou today's question -729 My schedule I
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 6](/img/38/51797fcdb57159b48d0e0a72eeb580.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 6
![[ruoyi] enable Mini navigation bar](/img/28/a8b38aecd90c8ddc98333f0e2d3eab.png)
[ruoyi] enable Mini navigation bar

Httprunnermanager installation (III) - configuring myql Database & initialization data under Linux

MySQL advanced notes

【若依(ruoyi)】设置主题样式

C # create self host webservice

华为、H3C、思科命令对比,思维导图形式从基础、交换、路由三大方向介绍【转自微信公众号网络技术联盟站】
随机推荐
A copy can also produce flowers
A doctor's 22 years in Huawei
1. Dynamic parameters of function: *args, **kwargs
Introduction to robotframework (II) app startup of appui automation
力扣今日题-729. 我的日程安排表 I
Detailed use of dbutils # yyds dry goods inventory #
力扣今日題-729. 我的日程安排錶 I
Misc (eternal night), the preliminary competition of the innovation practice competition of the National College Students' information security competition
MySQL winter vacation self-study 2022 11 (8)
Prototype design
Fault analysis | analysis of an example of MySQL running out of host memory
Atcoder beginer contest 233 (a~d) solution
The difference between sizeof and strlen in C language
解决:AttributeError: ‘str‘ object has no attribute ‘decode‘
[Digital IC manual tearing code] Verilog asynchronous reset synchronous release | topic | principle | design | simulation
[pointer training - eight questions]
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 14
tcpdump: no suitable device found
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 22
Technology sharing | what if Undo is too big