You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何跨模块为SQLAlchemy映射类添加关联且不修改原模块

解决方案

要在不修改module_1.py的前提下为User类添加双向关联,你可以利用Python类的动态特性,直接在module_2.py中为User类追加属性,具体实现如下:

修改后的module_2.py代码

# module_2.py
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy import ForeignKey
from typing import Set

from .module_1 import Base, User

class Address(Base):
    id: Mapped[int] = mapped_column(primary_key=True)
    city: Mapped[str]
    user_id: Mapped[int] = mapped_column(
        ForeignKey('user.id'), nullable=False
    )

    user: Mapped['User'] = relationship(back_populates='addresses')

# 为User类动态添加addresses关联属性
User.addresses: Mapped[Set['Address']] = relationship(back_populates='user')

关键说明

  • Python类属于动态对象,允许在类定义完成后直接追加属性,这是实现该需求的核心依据
  • 通过User.addresses赋值的方式,为module_1中定义的User类添加了双向关联属性,与Address类的user属性通过back_populates完成绑定,满足不使用backref的要求
  • 需补充导入relationship、ForeignKey和Set,确保所有依赖项齐全

内容的提问来源于stack exchange,提问作者Dante

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 07:29:58