【问题标题】:SqlAlchemy: Join onto another objectSqlAlchemy:加入另一个对象
【发布时间】:2013-06-17 12:57:44
【问题描述】:

我的小网站有一张 cmets 表和一张选票表。网站的每个用户都可以对每条评论进行一次投票。

在向用户显示 cmets 时,我将从 cmets 表中进行选择,如果当前用户存在投票,我将进行外连接。

有没有办法通过comment.my_vote 查询将投票附加到评论?

我现在这样做的方式是,查询为每个结果返回一个列表 - [comment, vote] - 我将它直接传递给我的模板。如果投票可以是评论的子对象,我更愿意。

【问题讨论】:

  • 你能发布你的代码吗?如果您将其缩减为三件事会很有帮助:sqlalchemy 定义、传递给模板的当前代码,以及一些说明您希望传递给模板的伪代码。

标签: python sqlalchemy


【解决方案1】:

设置您的模型以添加One-to-one relationship。链接中的示例代码:

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child = relationship("Child", uselist=False, backref="parent", 
        # lazy='joined', # @note: optional: uncomment this to have the 'child' always loaded when the parent is loaded.
    )

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parent.id'))

在您的情况下,Parent 将是 CommentChild 将是 Vote
然后可以查询Comment,同时热切加载Vote。为此,建议仅取消注释上面注释掉的行,以便您的查询将在一个 SQL 语句中返回所有内容。或者,您可以使用joinedload 在查询中明确指定加载Vote

res = query(Parent).options(joinedload(Parent.child))

【讨论】:

  • 不是一对一,因为多个用户可以对同一个评论进行投票
【解决方案2】:

最后我决定使用查询返回的元组不是问题。

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 2021-07-14
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多