我正在尝试使用棉花糖的 .load() 方法来反序列化 POST 请求上的 json 对象。但是我一直遇到这个错误'dict' object has no attribute '_sa_instance_state'
用户和角色有多对多的关系。模式上的 .dump() 工作正常,但 .load() 可以保存除多个角色之外的所有其他字段。我试图在我的 json 正文中传递它。
{
"last_name": "Fin",
"roles": [{"id": 3, "role": "admin"}],
"email": "test3@test.com",
"first_name": "Al",
"access_id": "ec1235",
"password": "1234567"
}
我的用户和角色模型
user_role = db.Table('user_role',
db.Column('user_id', db.ForeignKey('user.id')),
db.Column('role_id', db.ForeignKey('role.id')),
db.Column('properties', JSONType),
)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(80), nullable=False)
last_name = db.Column(db.String(80), nullable=False)
access_id = db.Column(db.String(6), unique=True, nullable=False)
email = db.Column(EmailType, unique=True, nullable=False)
password = db.Column(db.String(80), nullable=False)
roles = db.relationship('Role', secondary=user_role, backref='user', cascade="all")
class Role(db.Model):
id = db.Column(db.Integer, primary_key=True)
role = db.Column(db.String(20), nullable=False)
我的架构
class RoleSchema(ma.SQLAlchemyAutoSchema):
class Meta:
fields = ("id", "role")
model = Role
class UserSchema(ma.SQLAlchemyAutoSchema):
roles = ma.Nested(RoleSchema, many=True)
class Meta:
load_instance = True
fields = ("id", "first_name", "last_name", "access_id", "email", "roles, "password")
model = User
发布请求
def post(self):
try:
body = request.get_json()
user = user_schema.load(body)
user.hash_password()
db.session.add(user)
db.session.commit()
return {'id': str(user.id)}, 200
except Exception as e:
raise Exception("")