当前位置:   article > 正文

sqlalchemy 使用不同文件中的数据模型_sqlathanor

sqlathanor

要使用不同文件中的数据模型,就要让这些模型继承自同一个Base

base.py

  1. from sqlalchemy import create_engine, MetaData
  2. from sqlalchemy.orm import sessionmaker
  3. from sqlalchemy.ext.declarative import declarative_base
  4. engine = create_engine('sqlite:///test.db', echo=True) #可以看到调试信息
  5. Base = declarative_base()
  6. metadata = MataData(engine)
  7. Session = sessionmaker()
  8. Session.configure(bind=engine)
  9. session = Session()

user.py

  1. from sqlalchemy import Column,Integer,String, ForeignKey, create_engine, MetaData
  2. from sqlalchemy.orm import relationship
  3. from base import engine, Base
  4. from group import UserGroup
  5. user_usergroup = Table('user_usergroup',Base.metadata,
  6. Column('user_id', Integer, ForeignKey('user.id')),
  7. Column('usergroup_id', Integer, ForeignKey('user_group.id'))
  8. )
  9. class User(Base):
  10. __tablename__ = 'user'
  11. id = Column(Integer, primary_key=True)
  12. name = Column(String(30))
  13. group = relationship('UserGroup',
  14. secondary=user_usergroup,
  15. backref='User'
  16. )
  17. Base.metadata.create_all(engine)

group.py

  1. from sqlalchemy import Column,Integer,String, ForeignKey, create_engine, MetaData
  2. from sqlalchemy.orm import relationship
  3. from base import engine, Base
  4. class UserGroup(Base):
  5. __tablename__ = 'user_group'
  6. id = Column(Integer, primary_key=True)
  7. name = Column(String(30))
  8. Base.metadata.create_all(engine)






声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/569837
推荐阅读
相关标签
  

闽ICP备14008679号