簡體   English   中英

SQLAlchemy聲明性表上的多對多關系

[英]SQLAlchemy many-to-many relationship on declarative tables

我聲明性地定義了以下表(非常簡化的版本):

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表的多對多關系?

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

那就對了。 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")

    ...

此外, 您不應在Answer的init函數中設置profile_id和question_id的值 ,因為ORM負責根據您對對象的關系屬性的賦值來相應地設置它們。

您可能對閱讀聲明性文檔感興趣,尤其是關於配置關系的部分。 閱讀有關使用相關對象的信息也許有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM