我在我的应用程序中建立了一个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?
在这种情况下,必须显式地编写
primaryjoin
和secondaryjoin
条件:我编写这个示例是为了帮助您更好地理解
primaryjoin
和secondaryjoin
参数的含义。当然,你可以用backref
把它分类。顺便说一下,下表中不需要
id
列,而是使用复合主键。实际上,无论如何,您都应该定义follower_id
和followee_id
对的唯一约束(作为主键或附加的唯一键)。您还可以声明性地执行此操作。
下面是一个基于上述代码的类似示例,我确实使用了backref。
相关问题 更多 >
编程相关推荐