2010-07-04 74 views
10

我已聲明性地定義的下表(非常簡化的版本):SQLAlchemy的許多一對多關係聲明性表

class Profile(Base): 
     __tablename__ = 'profile' 

     id = Column(Integer, primary_key = True) 
     name = Column(String(65), nullable = False) 

     def __init__(self, name): 
      self.name = name 


class Question(Base): 
    __tablename__ = 'question' 

    id = Column(Integer, primary_key = True) 
    description = Column(String(255), nullable = False) 
    number = Column(Integer, nullable = False, unique = True) 


    def __init__(self, description, number): 
     self.description = description 
     self.number = number 



class Answer(Base): 
    __tablename__ = 'answer' 

    profile_id = Column(Integer, ForeignKey('profile.id'), primary_key = True) 
    question_id = Column(Integer, ForeignKey('question.id'), primary_key = True) 
    value = Column(Integer, nullable = False) 


    def __init__(self, profile_id, question_id, value): 
     self.profile_id = profile_id 
     self.question_id = question_id 
     self.value = value 

資料鏈接經由許多一對多關係對問題。在鏈接表(答案)中,我需要存儲答案的值。

該文件說我需要使用一個關聯對象來做到這一點,但它令我困惑,我無法讓它工作。

如何使用Answer作爲中介表爲Profile和Question表定義多對多關係?

回答

13

文檔說我需要使用 關聯對象要做到這一點,但 它混淆了我,我不能讓它 工作。

沒錯。而Answer類是你的關聯對象,因爲它映射到關聯表'答案'。

我如何定義配置文件,並使用答案爲 中介表 問表中的許多一對多 關係?

您在問題中提出的代碼是正確的。它只需要約在ORM階層關係的其他信息:

from sqlalchemy.orm import relationship 

... 

class Profile(Base): 
    __tablename__ = 'profile' 

    ... 

    answers = relationship("Answer", backref="profile") 

    ... 


class Question(Base): 
    __tablename__ = 'question' 

    ... 

    answers = relationship("Answer", backref="question") 

    ... 

此外,你應該在你的答案的初始化函數 PROFILE_ID和question_id沒有設置值,因爲它是這是負責將它們設置相應的基於ORM對你的對象的關係屬性進行分配。

你可能有興趣在閱讀documentation for declarative,尤其是部分約configuring relationships。閱讀約working with related objects也可能有所幫助。

+0

編輯修復斷開的文檔鏈接。 – rbp 2012-04-11 11:56:47

+0

這看起來不對。你的答案看起來像只通過多對一的關係將每一邊鏈接到關聯表。沒有提到多對多,即以下用法意味着orm級別的多對多:Profile.questions – 2014-02-24 19:46:31