SQLAlchemy单表上的多对多关系

时间:2009-12-11 16:39:51

标签: python orm sqlalchemy

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

2 个答案:

答案 0 :(得分:20)

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

以下是基于上述代码的类似示例,我使用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")

答案 1 :(得分:7)

在这种情况下,您必须明确写出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对的唯一约束(无论是主键还是其他唯一键)。