SQLAlchemy声明性表上的多对多关系

Vir*_*liu 10 python 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
Run Code Online (Sandbox Code Playgroud)

个人资料通过多对多关系链接到问题.在链接表(答案)中,我需要为答案存储一个值.

文档说我需要使用一个关联对象来做这个,但它让我感到困惑,我无法让它工作.

如何使用Answer作为中间表来定义Profile和Question表的多对多关系?

zif*_*fot 13

文档说我需要使用一个关联对象来做这个,但它让我感到困惑,我无法让它工作.

那就对了.Answer类是你的关联对象,因为它映射到关联表'answer'.

如何使用Answer作为中间表来定义Profile和Question表的多对多关系?

您在问题中提供的代码是正确的.它只需要有关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")

    ...
Run Code Online (Sandbox Code Playgroud)

此外,您不应在Answer的init函数中设置profile_id和question_id的值,因为ORM负责根据您对对象的关系属性的赋值来相应地设置它们.

您可能对阅读声明性文档感兴趣,尤其是关于配置关系的部分.阅读有关使用相关对象的信息也许有帮助.