Flask SQLALCHEMY Model 模型
class Person(db. Model):
__tablename__='person '
id = db.Column( db.Integer,primary_key=True)
name = db.Column(db.string(16),unique=True)
def __repr__(self):
return '<User {}>'.format(self.name)
字段类型(常用)
Integer
Float
String
常用约束
primary_key 主键 默认False
autoincrement 自动增长 默认False
unique 唯一 默认False
default 默认值
数据简单操作
创建数据库,表
db. create_all()
删除表
db. drop_all()
在事务中处理,数据插入
db.session.add(object)
db.session.commit()
获取所有数据
Person.query.all()
SQLAlchemy常用列类型
db.Column类构造函数的第一个参数代表数据类型,SQLAlchemy中基本包含了所有数据库中的类型,具体如下:
类型名 |
Python类型 |
说明 |
Integer |
int |
普通整数,32位 |
SmallInteger |
int |
16位整数 |
BigInteger |
int或long |
不限制精度整数 |
Float |
float |
浮点数 |
Numeric |
decimal.Decimal |
定点数 |
String |
str |
字符串 |
Text |
str |
长文本 |
Unicode |
unicode |
Unicode字符串 |
UnicodeText |
unicode |
长Unicode字符串 |
Boolean |
bool |
布尔值 |
Date |
datetime.date |
日期 |
Time |
datetime.time |
时间 |
Datetime |
datetime.datetime |
日期时间 |
Interval |
datetime.timedelta |
时间间隔 |
Enum |
str |
一组字符串 |
PickleType |
任何Python对象 |
使用Pickle序列化 |
LargeBinary |
str |
二进制blob |
SQLAlchemy常用列约束
约束名 |
说明 |
primary_key |
True代表主键 |
unique |
True代表值唯一 |
index |
True代表为列添加索引 |
nullable |
True代表允许使用空值 |
default |
这只列的默认值 |
ORM中的对应关系
模型 数据库
类 表数据
类属性 表字段
一个对象 表中的一行数据