【发布时间】:2018-02-05 15:17:10
【问题描述】:
我有两个对象,User 和 Room,它们都继承自 Base 对象。
class BaseModel:
__metaclass__ = Serializable
created = Column(DateTime, default=func.now())
modified = Column(DateTime, default=func.now(), onupdate=func.now())
@declared_attr
def __tablename__(self):
return self.__name__.lower()
Base = declarative_base(cls=BaseModel)
这是我的 User 模型,其中声明了与 Room 的多对多关联。
association_table = Table('users_rooms', Base.metadata,
Column('user_id', Integer, ForeignKey('user.id')),
Column('room_id', Integer, ForeignKey('room.id'))
)
class User(Base):
__table_args__ = {'extend_existing': True}
id = Column(Integer, primary_key=True)
mobile = Column(String(20), index=True, unique=True)
rooms = relationship("Room", secondary=association_table,
back_populates="users")
这就是房间模型。
association_table = Table('users_rooms', Base.metadata,
Column('user_id', Integer, ForeignKey('user.id')),
Column('room_id', Integer, ForeignKey('room.id'))
)
class Room(Base):
__table_args__ = {'extend_existing': True}
id = Column(Integer, primary_key=True)
room_type = Column(String(50), default=RoomType.PRIVATE)
hex_code = Column(String(100), unique=True)
users = relationship("User", secondary=association_table, back_populates="rooms")
当我尝试编译它时,我收到以下错误。
sqlalchemy.exc.InvalidRequestError: Table 'users_rooms' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
【问题讨论】:
标签: python orm sqlalchemy