Django的Models模型

ORM和原生SQL的优缺点:
优点:

  1. 实现了代码与数据操作的解耦合
  2. 不需自己写原生sql, 提高开发效率
  3. 防止SQL注入, 通过对象操作的方式,默认就是防止sql注入的。

缺点:

  1. 牺牲性能, 对象到原生SQL势必会有转换消耗,对性能有一定的影响
  2. 复杂语句力不从心, 一些复杂的sql语句,用orm对象操作的方式很难实现,就还得用原生sql

Models模型:

Django 的models把数据库表结构映射成了一个个的类, 表里的每个字段就是类的属性。我们都知道数据库有很多字段类型,int,float,char等, Django的models类针对不同的字段也设置了不同的类属性。

AutoField         #An IntegerField that automatically increments according to available IDs
BigAutoField      #A 64-bit integer, guaranteed to fit numbers from 1 to 9223372036854775807.
BigIntegerField   #-9223372036854775808 to 9223372036854775807
BinaryField       #A field to store raw binary data. It only supports bytes assignment
BooleanField   
CharField
DateField         #e.g 2019-04-27
DateTimeField     #e.g 2019-04-27 17:53:21
DecimalField     
DurationField     #storing periods of time ,e.g [DD] [HH:[MM:]]ss[.uuuuuu]"
EmailField
FileField         #存储文件
FloatField
ImageField        #Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image.
IntegerField
GenericIPAddressField #IP地址,支持ipv4
NullBooleanField      #Like a BooleanField, but allows NULL as one of the options
PositiveIntegerField  #Like an IntegerField, but must be either positive or zero (0). Values from 0 to 2147483647
PositiveSmallIntegerField #only allows positive  values from 0 to 32767
SlugField					 # A slug is a short label for something, containing only letters, numbers, underscores or hyphens.
SmallIntegerField
TextField  				 #A large text field.
TimeField  				 #A time, represented in Python by a datetime.time instance.
URLField
UUIDField 

除了普通的表字段,针对外键也有映射

ForeignKey  # 外键关联
ManyToManyField  #多对多
OneToOneField  # 1对1

猜你喜欢

转载自blog.csdn.net/qq_39655431/article/details/83625954
今日推荐