gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:27:01 30 4
gpt4 key购买 nike

我以声明方式定义了下表(非常简化的版本):

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 表的多对多关系?

最佳答案

The documentation says I need to use an association object to do this but it's confusing me and I can't get it to work.

没错。 Answer 类是您的关联对象,因为它映射到关联表“answer”。

How do I define the many-to-many relationship for the Profile and Question tables using Answer as the intermediary table?

您在问题中提供的代码是正确的。它只需要有关 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 的初始化函数中设置 profile_id 和 question_id 的值,因为 ORM 负责根据您对对象的关系属性的分配来相应地设置它们。

您可能有兴趣阅读 documentation for declarative ,尤其是关于 configuring relationships的部分 。阅读关于 working with related objects 也可能有帮助。

关于python - 声明性表上的 SQLAlchemy 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3174979/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com