SQLAlchemy操作数据库建表时,无法像Django一样提供choice方法,我们开头导入SQLAlchemy-Utils来为我们提供这个功能
pip3 install sqlalchemy-utils
from sqlalchemy_utils import ChoiceType Base = declarative_base() class Xuan(Base): __tablename__ = 'xuan' types_choices = ( (1,'欧美'), (2,'日韩'), (3,'国产'), ) id = Column(Integer,primary_key=True,autoincrement=True) name = Column(String(64)) types = Column(ChoiceType(types_choices,Integer())) __table_args__ = { 'mysql_engine':'Innodb', 'mysql_charset':'utf8', }
查询:
result_list = session.query(Xuan).all() for item in result_list: print(item.types.code,item.types.value)