【发布时间】:2018-04-24 20:52:52
【问题描述】:
我正在构建一个模型来存储具有一组属性的电子邮件:
email_list_table = Table('email_list', Base.metadata,
Column('email_id', String, ForeignKey('emails.id')),
Column('list_id', Integer, ForeignKey('lists.id'))
)
class Email(Base):
__tablename__ = 'emails'
id = Column(String, primary_key=True)
from_email = Column(String, nullable=False)
from_name = Column(String, nullable=False)
date = Column(DateTime, nullable=False)
in_reply_to = Column(String)
subject = Column(String, nullable=False)
content = Column(String, nullable=False)
lists = relationship("List", secondary=email_list_table)
references = relationship("Email") # This is the issue
def __repr__(self):
return "<Email(id='%s', from='%s', subject='%s')>" % (self.id, self.from_name, self.subject)
class List(Base):
__tablename__ = 'lists'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
email = Column(String, nullable=False)
description = Column(String, nullable=False)
def __repr__(self):
return "<List(id='%s')>" % (self.id)
我想将references 关系表示为电子邮件列表。例如,一封电子邮件可以引用不止一封其他电子邮件,并被多个电子邮件引用。
在传统 SQL 中,我将使用第二个表,其复合主键为 referrer_id 和 referenced_id,并且在查询时我会加入这两个表以获取我的引用电子邮件列表。这样可以很容易地找到给定 ID 引用了哪些电子邮件以及给定 ID 引用了哪些电子邮件。
我查看了Adjacency List Relationships 的 SQLAlchemy 文档,但我不确定那里的示例是否适用于我的模型(我想我可以为 referrer_id 添加一列,但这不会产生相同的表结构正如我所料,使用“加入”表)。
使用 SQLAlchemy 生成我期望的模型的最佳/最正确方法是什么?
【问题讨论】:
标签: python sqlalchemy