开发者

Modeling a database many to many relationship between three tables using sqlalchemy in python

Let's consider the followi开发者_StackOverflow社区ng 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. :-))

  1. A worker may have multiple projects to work on.
  2. A project may have multiple workers assigned to work on it.
  3. For each tuple (worker, project) you have a distinct rating

I understand, that I have three many to many relationship. Those are:

  1. worker and project
  2. worker and rating
  3. 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.


Make the ratings table something like this.

  Rating
---------------------
  rating_id (primary key) 
  worker_id (foreign key - worker(worker_id)) 
  project_id (foreign key - project(project_id)) 
  description

If I'm understanding this correctly that is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜