sqlalchemy中Column的默许值属性
在SQLAlchemy中,`Column`的默许值可以通过在`Column`的构造函数中使用`default`参数来设置。`default`参数可以是一个值、一个函数或一个SQL表达式。
以下是一些常见的用法示例:
1. 默许值为常量值:
```python
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String, default='John')
```
在上面的示例中,`name`列的默许值设置为`'John'`。
2. 默许值为函数的返回值:
```python
from sqlalchemy import Column, Integer, func
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
created_at = Column(DateTime, default=func.now())
```
在上面的示例中,`created_at`列的默许值设置为当前时间。
3. 默许值为SQL表达式:
```python
from sqlalchemy import Column, Integer, text
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
active = Column(Integer, default=text('1'))
```
在上面的示例中,`active`列的默许值设置为SQL表达式`1`。
需要注意的是,默许值的计算是在数据库层面上进行的,而不是在Python层面上进行的。因此,使用Python函数作为默许值时需要使用SQLAlchemy提供的函数(如`func.now()`)来代替Python的内置函数(如`datetime.now()`)。另外,还需要注意默许值函数或SQL表达式的返回类型一定要与列的类型相匹配。
TOP