【问题标题】:Get Particular Columns in SQLAlchemy获取 SQLAlchemy 中的特定列
【发布时间】:2021-12-30 11:54:11
【问题描述】:

Table Schema

我有三个表,其架构如图中定义,我想要 id、title、content、published、created_at 来自 posts 表、username 来自 Users 表以及帖子的总投票数 在投票表中,对于每个由用户投票,创建一个新条目,由帖子 ID 和用户 ID 组成

我试过了-

all_posts = db.query(
    func.count(models.Vote.post_id), models.User.username,
    models.Post.id, models.Post.title,
    models.Post.content, models.Post.created_at
).filter(
    models.Post.user_id == models.User.id,
    models.Vote.post_id == models.Post.id
).group_by(
    models.User.username, models.Post.id, models.Post.title,
    models.Post.content, models.Post.created_at
)

输出 - Output

username: 'User1'
id: 1
title: Title 1
content: Content 1
created_at: '2021-11-18T12:13:09.236169+05:30'

在我指定的查询中,我也想要计票,但在输出中我没有得到票数

【问题讨论】:

  • 欢迎来到 Stackoverflow。请在此问题中包含输出(作为文本)。输出有什么问题?
  • @Donat 我得到了除票数列之外的所有列 `

标签: python sqlalchemy flask-sqlalchemy


【解决方案1】:

由于您的表之间已经有外键,您可以尝试在模型上定义relationships。

class Post(Base):
    # rest of the model omitted but unchanged
    creator = relationship("User")
    votes = relationship("Vote", back_populates="post")

class Vote(Base):
    # rest of the model omitted but unchanged
    post = relationship("Post", back_populates="votes")

有了这些新的关系,得到你需要的计数和属性就很简单了:

# the joins are to avoid any unwanted cartesian products
(
    s.dbs.query(
            Post.id,
            User.username,
            func.count(Post.votes)
        )
        .join(Vote.post)
        .join(Post.creator)
        .group_by(
            Post.id,
            User.username
    ).all()
)

【讨论】:

    猜你喜欢
    • 2021-11-22
    • 2012-02-23
    • 2021-09-01
    • 2018-01-25
    • 2014-02-22
    • 2011-09-22
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多