单个选项卡上的SQLAlchemy多个关系

2024-09-27 04:26:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的应用程序中建立了一个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?


Tags: 模型idfalsetrue关系satablecolumn
2条回答

在这种情况下,必须显式地编写primaryjoinsecondaryjoin条件:

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),
        ),
    },
)

我编写这个示例是为了帮助您更好地理解primaryjoinsecondaryjoin参数的含义。当然,你可以用backref把它分类。

顺便说一下,下表中不需要id列,而是使用复合主键。实际上,无论如何,您都应该定义follower_idfollowee_id对的唯一约束(作为主键或附加的唯一键)。

您还可以声明性地执行此操作。

下面是一个基于上述代码的类似示例,我确实使用了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")

相关问题 更多 >

    热门问题