SQLAlchemy常用字段
2018-07-14 本文已影响0人
_LC
安装:sudo pip3 install sqlalchemy
model定义
首先导入from sqlalchemy.ext.declarative import declarative_base
然后创建一个实例,Base=declarative_base(),后面所有定义的model都是Base的子类,继承Base。
model中一条数据类似于Excel的行,使用Column。
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String
Base=declarative_base()
class User(Base):
__tablename__='user'
id=Column(Integer,primary_key=True,autoincrement=True)
name=Column(String(20),unique=True,nullable=False)
pwd=Column(String(100),nullable=False)
info=Column(Text)
def __repr__(self):
return '<User %r>'%self.name
数据库的连接
from sqlalchemy import create_engine
eng=create_engine(DB_URI)
DB_URI的格式如下:dialect+driver://username:password@host:port/database
例如Mysql,DB_URI=mysql+mysqlclient://scott:tiger@localhost/foo
1.常用字段类型
| 类型 | python中类型 | 说明 |
|---|---|---|
| Integer | int | 普通整数,一般是32位 |
| SmallInteger | int | 取值范围小的整数,一般是16位 |
| BigInteger | int/long | 不限制精度的整数 |
| Float | float | 浮点数 |
| Numeric | decimal.Decimal | 普通整数,一般是32位 |
| String | str | 变长字符串,一般String(10)注明长度 |
| Text | str | 变长字符串,对较长或不限长度的字符串做了优化,不用指明长度 |
| Unicode | unicode | 变长Unicode字符串 |
| UnicodeText | unicode | 变长Unicode字符串,对较长或不限长度的字符串做了优化 |
| Boolean | boolean | 布尔值 |
| Date | datetime.date | 时间 |
| Time | time | 时间和日期 |
| LagreBinary | str | 二进制文件 |
2. 常用列选项
| 选项 | 说明 |
|---|---|
| primary_key | 主键,True、False |
| unique | 如果为True,代表这列不允许出现重复的值 |
| index | 如果为True,为这列创建索引,提高查询效率 |
| nullable | 如果为True,允许有空值,如果为False,不允许有空值 |
| default | 定义默认值 |
3. 关系选项
| 选项 | 说明 |
|---|---|
| backref | 在关系的另一模型中添加反向引用 |
| primaryjoin | 明确指定两个模型之间使用的联结条件 |
| uselist | 如果为False,不使用列表,而使用标量值 |
| order_by | 指定关系中记录的排序方式 |
| secondary | 指定多对多中记录的排序方式 |
| secondaryjoin | 在SQLAlchemy中无法自行决定时,指定多对多关系中的二级联结条件 |