2010-07-04 75 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