要使用不同文件中的数据模型,就要让这些模型继承自同一个Base
base.py
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///test.db', echo=True) #可以看到调试信息
Base = declarative_base()
metadata = MataData(engine)
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
user.py
from sqlalchemy import Column,Integer,String, ForeignKey, create_engine, MetaData
from sqlalchemy.orm import relationship
from base import engine, Base
from group import UserGroup
user_usergroup = Table('user_usergroup',Base.metadata,
Column('user_id', Integer, ForeignKey('user.id')),
Column('usergroup_id', Integer, ForeignKey('user_group.id'))
)
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(30))
group = relationship('UserGroup',
secondary=user_usergroup,
backref='User'
)
Base.metadata.create_all(engine)
group.py
from sqlalchemy import Column,Integer,String, ForeignKey, create_engine, MetaData
from sqlalchemy.orm import relationship
from base import engine, Base
class UserGroup(Base):
__tablename__ = 'user_group'
id = Column(Integer, primary_key=True)
name = Column(String(30))
Base.metadata.create_all(engine)