python-3.x - AttributeError:“dict”对象没有属性“_sa_instance_state”
问题描述
我正在使用and创建一个flask_restful
API 。这是我的模型sqlalchemy
marshmallow
class User(db.Model):
"""Basic user model
"""
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(255), nullable=False)
active = db.Column(db.Boolean, default=True)
is_admin = db.Column(db.Boolean, default=False)
profile = db.relationship("Profile", back_populates="user", uselist=False)
class Profile(db.Model):
"""Profile model
"""
id = db.Column(db.Integer, primary_key=True)
fullname = db.Column(db.String(80), unique=False, nullable=True)
img_url = db.Column(db.String(255), unique=False, nullable=True)
telephone = db.Column(db.String(20), unique=False, nullable=True)
user_id = db.Column(
db.Integer,
db.ForeignKey('user.id'),
nullable=False)
user = db.relationship("User", back_populates="profile")
这里是用于更新PUT
请求的用户资源
class UserResource(Resource):
def put(self, user_id):
schema = UserSchema()
user = User.query.get_or_404(user_id)
data = {
'username': 'updated',
"password": 'HRcdxRu45',
'email': 'ms@gt.vom',
'profile': {
'telephone': '+2507800112233',
'fullname': 'Mic Lolo',
'img_url': 'images/img.jpg'
}
}
user = schema.load(data, instance=user)
return {"message": "user updated", "data": schema.dump(user)}
这是我的架构
class ProfileSchema(ma.Schema):
id = ma.Int(dump_only=True)
fullname = ma.Str(validate=Length(min=3, max=80, error='empty fullname'))
img_url = ma.Str(validate=Length(min=3, max=80, error='empty image url'))
telephone = ma.Str(validate=Regexp(regex=r"\+[0-9]{7,13}", error="Invalid phone number"))
class Meta:
model = Profile
sqla_session = db.session
class UserSchema(ma.ModelSchema):
id = ma.Int(dump_only=True)
password = ma.Str(load_only=True,
validate=Length(min=8, max=255, error='empty password'))
username = ma.Str(validate=Length(min=3, max=80, error='empty username'))
is_admin = ma.Bool()
email = ma.Email()
profile = ma.Nested(ProfileSchema)
class Meta:
model = User
sqla_session = db.session
我得到 AttributeError:'dict' 对象没有属性 '_sa_instance_state'
当我从中删除嵌套的配置文件架构时,UserSchema
没有错误,但user.profile
不会更新。此外,当我在没有错误的情况下删除instance=user
参数并且我将获得一个带有已发布数据的良好用户实例时,这里的问题再次是该用户实例与数据库中现有的用户实例之间没有任何链接,我将不得不schema.load(data, instance=user)
手动查找要更新的用户字段。
解决方案
class ProfileSchema(ma.Schema):
ProfileSchema
应该继承自ma.ModelSchema
推荐阅读
- ruby-on-rails - 在事务中对同一 ActiveRecord 对象进行多次更新后,after_commit 中的陈旧数据
- scala - 根据Scala中其他Seq的值对一个Seq进行排序
- macos - macOS:将 NullAudio 示例缩减为没有输出
- elasticsearch - 如何按弹性搜索响应字段设置特定顺序?
- java - android studio生成签名apk问题(找不到kotlin-compiler-27.0.1.jar)
- data-structures - 我们需要最短路径树的任何现实问题?
- shell - shell中的sql语句被pwd中的文件名替换
- r - 计算 3D 网格的旋转平移
- javascript - 元素添加到 DOM 但不可见
- php - 如何将 CryptoJS.AES.encrypt NodeJS 转换为 PHP