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. :-))
- A workermay have multipleprojectsto work on.
- A projectmay have multipleworkersassigned 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.
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.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论