![](/img/trans.png)
[英]SQLAlchemy Many-to-Many Relationship on a Single Table Error: NoReferencedTableError
[英]SQLAlchemy Many-to-Many Relationship on a Single Table
我在我的应用程序中设置了一个SQLAlchemy模型,它应该模仿Twitter上“关注者”的功能,即。 用户与彼此之间存在多对多关系(关注者和关注者)。 这些表的结构如下(sa是sqlalchemy模块):
t_users = sa.Table("users", meta.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("email", sa.types.String(320), unique=True, nullable=False),
...etc...
)
t_follows = sa.Table("follows", meta.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("follower_id", sa.types.Integer, sa.ForeignKey('users.id'), nullable=False),
sa.Column("followee_id", sa.types.Integer, sa.ForeignKey('users.id'), nullable=False)
)
我遇到了一些障碍,但是尝试使用orm.mapper来创建这种关系,因为辅助表在两个方向上都引用了相同的主表。 我如何将这种关系映射到ORM?
您也可以声明性地执行此操作。
这是一个基于上面代码的类似示例,我使用backref。
VolumeRelationship = Table(
'VolumeRelationship', Base.metadata,
Column('ParentID', Integer, ForeignKey('Volumes.ID')),
Column('VolumeID', Integer, ForeignKey('Volumes.ID'))
)
class Volume(Base):
""" Volume Object """
__tablename__ = "Volumes"
id = Column('ID', Integer, primary_key=True, nullable=False)
type = Column('Type', String(25))
name = Column('Name', String(25))
poolid = Column('pool', Integer, ForeignKey('Pools.ID'))
parents = relation(
'Volume',secondary=VolumeRelationship,
primaryjoin=VolumeRelationship.c.VolumeID==id,
secondaryjoin=VolumeRelationship.c.ParentID==id,
backref="children")
在这种情况下,您必须显式编写primaryjoin
和secondaryjoin
条件:
mapper(
User, t_users,
properties={
'followers': relation(
User,
secondary=t_follows,
primaryjoin=(t_follows.c.followee_id==t_users.c.id),
secondaryjoin=(t_follows.c.follower_id==t_users.c.id),
),
'followees': relation(
User,
secondary=t_follows,
primaryjoin=(t_follows.c.follower_id==t_users.c.id),
secondaryjoin=(t_follows.c.followee_id==t_users.c.id),
),
},
)
我已经编写了这个示例详细信息,以帮助您更好地理解primaryjoin
和secondaryjoin
参数的含义。 当然,你可以使用backref
进行分类。
顺便说一句,您不需要在下表中使用id
列,而是使用复合主键。 实际上,无论如何都应该定义follower_id
和followee_id
对的唯一约束(作为主要或附加的唯一键)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.