在当前稳定的 SQLAlchemy 版本中,没有将模型映射到数据类的方法(应该在 v1.4 中可用)。所以我想通过定义来应用我自己的 ORM:
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String)
def __init__(self, name: str):
self.name = name
class UserSchema(SQLAlchemyAutoSchema):
class Meta:
model = User
load_instance = True
user_schema = UserSchema()
我的目标是使用模式从 REST API 加载 json 数据。但似乎自动递增的主键id
是个问题。因为属性id
只在数据库中定义,而不在属性列表中。所以当我申请时user_schema.load(#some_json)
,我得到了错误报告TypeError: __init__() got an unexpected keyword argument 'id'
跟踪误差是这样的:
@ma.post_load
def make_instance(self, data, **kwargs):
"""Deserialize data to an instance of the model if self.load_instance is True.
Update an existing row if specified in `self.instance` or loaded by primary key(s) in the data;
else create a new row.
:param data: Data to deserialize.
"""
if not self.opts.load_instance:
return data
instance = self.instance or self.get_instance(data)
if instance is not None:
for key, value in data.items():
setattr(instance, key, value)
return instance
kwargs, association_attrs = self._split_model_kwargs_association(data)
> instance = self.opts.model(**kwargs)
E TypeError: __init__() got an unexpected keyword argument 'id'
../../environments/xxx/lib/python3.7/site-packages/marshmallow_sqlalchemy/schema/load_instance_mixin.py:74: TypeError
我的问题是,我应该如何定义模型类,目的是我可以将它用作普通数据类,同时也是 SQLAlchemy 中的 ORM 模型?