Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法映射SQLAlchemy中的多对多关系_Python_Orm_Sqlalchemy - Fatal编程技术网

Python 无法映射SQLAlchemy中的多对多关系

Python 无法映射SQLAlchemy中的多对多关系,python,orm,sqlalchemy,Python,Orm,Sqlalchemy,我有两个对象,User和Room,它们都继承自一个基本对象 这是我的用户模型,上面声明了和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): __tab

我有两个对象,User和Room,它们都继承自一个基本对象

这是我的用户模型,上面声明了和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")
这是房间模型

当我试图编译它时,我得到以下错误

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.

错误试图告诉您不需要也不应该在两个模块中定义关联表。在其中一个或其自身的模块中定义它,然后导入它,或使用secondary=users\u rooms在关系中懒洋洋地引用它:

表名作为传入的字符串值从与房间模型关联的元数据集合中查找

你也不需要洒水

__table_args__ = {'extend_existing': True}

在你的模型中。如果在没有它的情况下出现与本问题类似的错误,则在构建模型之前,表已经创建并包含在元数据集合中。例如,您可能使用了反射。

效果非常好。
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.
# Room model. Note the absence of `association_table`

class Room(Base):

    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="users_rooms", back_populates="rooms")
__table_args__ = {'extend_existing': True}