【问题标题】:How to define one-to-one and many-to-many relationship using SQLAlchemy Core如何使用 SQLAlchemy Core 定义一对一和多对多关系
【发布时间】:2020-07-23 23:30:09
【问题描述】:

我已经搜索了文档,但没有发现任何有用的信息。请指引我正确的方向。

【问题讨论】:

  • 就像在 SQL 中一样,定义外键约束和可能的关联表。
  • 你的意思是使用sqlalchemy.orm.relationship 对吧?
  • @IljaEverilä 你能指出我正确的方向吗
  • 不,正如限定名称所指出的,relationship() 是一个 ORM 概念,用于将对象关系映射到关系关系。在关系数据库中,您使用外键约束(可能还有其他约束)定义关系(表)之间的关系。在 SQLAlchemy Core 中,您使用 ForeignKeyForeignKeyConstraint 表示外键约束:docs.sqlalchemy.org/en/latest/core/constraints.html
  • 是的。引用SQL Expression Language Tutorial:“SQLAlchemy 表达式语言提供了一个使用 Python 构造表示关系数据库结构和表达式的系统。”换句话说,使用 Core,您可以使用 Python 表示的关系数据库方式来做事。

标签: sqlalchemy


【解决方案1】:

一对一

使用一个表的 id 作为另一个表的外键和主键。

来自overiq的示例

employees = Table('employees', metadata,
    Column('employee_id', Integer(), primary_key=True),
    Column('first_name', String(200), nullable=False),
    Column('last_name', String(200), nullable=False),
    Column('dob', DateTime(), nullable=False),
    Column('designation', String(200), nullable=False),
)

employee_details = Table('employee_details', metadata,
    Column('employee_id', ForeignKey('employees.employee_id'), primary_key=True, ),
    Column('ssn', String(200), nullable=False),
    Column('salary', String(200), nullable=False),
    Column('blood_group', String(200), nullable=False),
    Column('residential_address', String(200), nullable=False),    
)

多对一

来自SQL Alchemy's official docs

在 SQLAlchemy 和 DDL 中,外键约束可以定义为 table 子句中的附加属性,或者对于单列外键,它们可以选择在单列的定义中指定。单列外键比较常见,在列级别通过构造 ForeignKey 对象作为 Column 对象的参数来指定:

user_preference = Table('user_preference', metadata,
    Column('pref_id', Integer, primary_key=True),
    Column('user_id', Integer, ForeignKey("user.user_id"), nullable=False),
    Column('pref_name', String(40), nullable=False),
    Column('pref_value', String(100))
)

多对多

使用两个外键创建第三个表,这些表引用要在它们之间创建关系的表

来自overiq的示例

posts = Table('posts', metadata,
    Column('id', Integer(), primary_key=True),
    Column('post_title', String(200), nullable=False),
    Column('post_slug', String(200),  nullable=False),
    Column('content', Text(),  nullable=False),    
)

tags = Table('tags', metadata,
    Column('id', Integer(), primary_key=True),
    Column('tag', String(200), nullable=False),
    Column('tag_slug', String(200),  nullable=False),    
)

post_tags = Table('post_tags', metadata,
    Column('post_id', ForeignKey('posts.id')),
    Column('tag_id', ForeignKey('tags.id'))
)

【讨论】:

    猜你喜欢
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2016-06-15
    • 2021-08-31
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    相关资源
    最近更新 更多