在Python中使用sqlalchemy对三个表之间的数据库多对多关系进行建模
让我们考虑一下 python 中 sqlalchemy 的以下表模型。
class Worker(Base):
id Column(Integer, primary = True)
name Column(String, nullable = False)
class Project(Base):
id Column(Integer, primary = True)
name Column(String, nullable = False)
class Rating(Base):
id Column(Integer, primary = True)
description Column(String, nullable = False)
让我们考虑一下这些表的一些限制。 (请不要质疑这个例子的意义,这是我想出的最好的来描述我想学习的内容。:-))
- 一个
worker
可能有多个项目
继续工作。 - 一个
项目
可能会分配多个工作人员
来处理它。 - 对于每个元组
(worker,project)
,你都有一个不同的评级
我理解,我有三个多对多的关系。这些是:
- 工人和项目
- 工人以及评级
- 评级和项目
我可以毫无问题地定义两个表之间的多对多关系。我只需将以下关联表和关系添加到我的模型中。
worker_project = Table('worker_project', METADATA,
Column('worker_id', Integer, ForeignKey('workers.id')),
Column('project_id', Integer, ForeignKey('projects.id')),
class Worker(Base):
# [...]
papers = relationship('Project',
secondary=worker_project,
backref='workers')
我失败的是像上面描述的那样链接表“评级”。任何帮助都是值得赞赏的。
Let's consider the following table models for sqlalchemy in python.
class Worker(Base):
id Column(Integer, primary = True)
name Column(String, nullable = False)
class Project(Base):
id Column(Integer, primary = True)
name Column(String, nullable = False)
class Rating(Base):
id Column(Integer, primary = True)
description Column(String, nullable = False)
Let's consider some restrictions on these tables. (Don't question the sense of this example please, it is the best I came up with to describe what I'd like to learn. :-))
- A
worker
may have multipleprojects
to work on. - A
project
may have multipleworkers
assigned to work on it. - For each tuple
(worker, project)
you have a distinctrating
I understand, that I have three many to many relationship. Those are:
- worker and project
- worker and rating
- rating and project
I have no problems defining a many to many relationship between two tables. I just would have to add the folowing association table and a realtionship to my models.
worker_project = Table('worker_project', METADATA,
Column('worker_id', Integer, ForeignKey('workers.id')),
Column('project_id', Integer, ForeignKey('projects.id')),
class Worker(Base):
# [...]
papers = relationship('Project',
secondary=worker_project,
backref='workers')
What I do fail in, is to link the table "ratings" like described above. Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让评级表像这样。
如果我理解正确的话那就是。
Make the ratings table something like this.
If I'm understanding this correctly that is.