SQLAlchemy的Column定义中常用的属性有哪些,分别举例
时间: 2023-12-10 11:06:07 浏览: 190
SQLAlchemy的Column定义中常用的属性有:
1. type:指定列的数据类型,常用的数据类型有String、Integer、Boolean、DateTime等。例如:
```python
from sqlalchemy import Column, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
```
2. primary_key:指定列是否为主键。例如:
```python
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
```
3. unique:指定列的值是否唯一。例如:
```python
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50), unique=True)
```
4. nullable:指定列是否可以为NULL。例如:
```python
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
```
5. default:指定列的默认值。例如:
```python
from sqlalchemy import Column, Integer, String, DateTime, func
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
created_at = Column(DateTime, default=func.now())
```
6. index:指定列是否创建索引。例如:
```python
from sqlalchemy import Column, Integer, String, Index
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
email = Column(String(50), unique=True, index=True)
idx_name_email = Index('idx_name_email', name, email)
```
7. server_default:指定数据库端默认值。例如:
```python
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
status = Column(Integer, server_default='0')
```
阅读全文