python - 如何在 SQLAlchemy 中连接两个表中的数据?

标签 python postgresql sqlalchemy flask-sqlalchemy

我有 3 个表:AccountUserOrganization

  • Accountidnameorganization_id组成。
  • Useremailorganization_id 组成。
  • Organizationidname 组成。

每个 Account 都注册到一个 Organization(通过 organization_id),每个 User 都注册到一个 组织。挑战是显示所有电子邮件(来自 User)到与 name 对应的 Account,其 organization_id 匹配用户organization_id

到目前为止,这是我的代码:

class Account(db.Model):
    __tablename__ = "account"
    id = Column(Integer, primary_key=True)
    name = Column(String(50), index=True, unique=True)
    organization = Column(Integer, 
        ForeignKey("organization.id"),nullable=False, index=True)

class User(UserMixin, db.Model, RBACUserMixin):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    organization = Column(Integer, ForeignKey("organization.id"), 
                      nullable=False, index=True)

class Organization(db.Model):
    __tablename__ = "organization"
    id = Column(Integer, primary_key=True)
    name = Column(String(512))
    users = relationship("User", backref="organizations")
    accounts = relationship("Account", backref="organizations")

最佳答案

根据组织 ID 加入用户和帐户,并根据名称进行过滤:

db.session.query(User.email).\
    join(Account, Account.organization == User.organization).\
    filter(Account.name == 'some name')

Query.join()允许在使用 2 参数形式时将任意 SQL 表达式作为 on-clause 传递。

关于python - 如何在 SQLAlchemy 中连接两个表中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50617343/

相关文章:

python - 如果可以使用文字初始化,如何包装自定义 C++ 类型以与 pybind11 一起使用?

python - Pandas DataFrame 基于条件的切片列

python - TypeError:图片应为PIL图像或ndarray。得到了<class ‘bool’>

sql - 递归 CTE 如何使用它

postgresql - 是否有替代 PostgreSQL 中的临时表来保存和操作结果集?

postgresql - gitlab备份还原影响url重定向

python - pandas dataframe header 与 sql 表头的关系

python - 在没有 sudo 的情况下使用 apt-get/yum

python-3.x - Snowflake Authentication Token expired (390114) - 是否有 Snowflake-SQLAlchemy 的心跳代码?

python - 使用 python 3 通过 SSH(通过跳转主机)连接到 MySQL 数据库