赞
踩
要使用不同文件中的数据模型,就要让这些模型继承自同一个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)
- 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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。