在 Flask SQLAlchemy 和 Marshamllow 模式中实现 IS-A 基数

问题描述 投票:0回答:1

假设我有一个名为

User
的表,其中包含系统中注册的所有用户的一般信息:

class User(db.Model):
    __tablename__ = 'User'

    id = db.Column(db.Integer, primary_key=True)
    role = db.Column(db.String(20), nullable=False)
    email = db.Column(db.String(256), unique=True, nullable=False)
    password = db.Column(db.String(256), nullable=False)
    sign_up_date = db.Column(db.DateTime, nullable=False)
    archived = db.Column(db.Integer, nullable=False, default=0)

然后我有两个用户子类型,每个子类型包含上述所有列,以及一些特定于类型的列。例如:

班级客户:

class Customer(User):
    __tablename__ = "Customer"
    # USER is a CUSTOMER
    address = db.Column(db.String(256), nullable=False)
    name = db.Column(db.String(64), nullable=False)

类驱动程序:

class Driver(User):
    __tablename__ = "Driver"
    # USER is a DRIVER
    first_name = db.Column(db.String(64), nullable=False)
    last_name = db.Column(db.String(64), nullable=False)
    profile_picture_path = db.Column(db.String(256), nullable=False)

类仓库经理:

class WarehouseManager(User):
    __tablename__ = "WarehouseManager"
    # USER is a WAREHOUSE MANAGER
    first_name = db.Column(db.String(64), nullable=False)
    last_name = db.Column(db.String(64), nullable=False)
    profile_picture_path = db.Column(db.String(256), nullable=False)
    warehouse_name = db.Column(db.String(64), nullable=False)

等等。

每当我尝试使用

db.create_all()
创建此问题时,都会出现问题,我收到以下错误:

sqlalchemy.exc.ArgumentError: Column 'first_name' on class WarehouseManager conflicts with existing column 'User.first_name'.  If using Declarative, consider using the use_existing_column parameter of mapped_column() to resolve conflicts.

而且我也不知道如何在 Marshmallow 中为此创建模式。

需要明确的是,我希望 Driver 的数据库包含

user_id
和所有附加字段(first_name、last_name、profile_picture_path),但是当我通过 SQLAlchemy 与数据库交互时,我希望能够输入
User 
Driver
 表中的 
列即:

driver = Driver(email="[email protected]", first_name="Driver Name"...)

而不是:

user = Users(email="[email protected]"...)
driver = Driver(user_id = user.id, first_name="Driver Name"...)

我认为在使用高质量 ORM 方面,阶梯是重复且糟糕的做法。高质量的 ORM 应该能够轻松处理这些常见情况。这不是我第一次对 ORM 的有限功能感到失望,尤其是在处理临时表、物化视图、触发器等时。

编辑: 我尝试在

use_existing_column
db.Column
中添加
first_name
。我仍然遇到同样的错误。

编辑2:

这里是一个重现问题的沙箱。

python sqlalchemy flask-sqlalchemy
1个回答
0
投票
SQLAlchemy 继承不起作用

也许这会帮助您解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.