sqlalchemy自定义映射表的元类有两种方式:函数declarative_base
和as_declarative
装饰器
- 通过继承
DeclarativeMeta
元类,在使用declarative_base
函数时传递给metaclass
参数
1 | from sqlalchemy import Column, Integer, Text, create_engine |
- 定义一个类并使用
as_declarative
装饰器,使之成为表映射类的元类
以下是官方文档的示例:
1 | from sqlalchemy.ext.declarative import as_declarative |
对比两种方式,as_declarative
装饰器的方式更加直观,代码易读性会高一些