我需要你的帮助
当我想从我的flask-backendserver用MariaDb返回带有SQLAlchemy的数组时,它总是像这样用引号引起来->“ [{obj},{obj},{obj}]”。
我的查询:
units = Unit.query.all()
print(units) --> [<Unit 1>, <Unit 2>, <Unit 3>, <Unit 4>, <Unit 5>, <Unit 6>, <Unit 7>, <Unit 8>, <Unit 9>, <Unit 10>]
result = units_schema.dumps(units).data
return {"msg": result}
但是我的结果看起来像这样:
{
"msg": "[{\"unit_name\": \"Name1\", \"unit_id\": \"ID_1\"},{\"unit_name\": \"Name2\", \"unit_id\": \"ID_2\"}]"
}
我的班级模型:
class Unit(db.Model):
__tablename__ = "unit_table"
id = db.Column(db.Integer, primary_key=True)
unit_name = db.Column(db.String(40))
unit_id = db.Column(db.String(40), unique=True)
created_at = db.Column(db.DateTime(timezone=True), server_default=(func.now()))
last_updated = db.Column(db.DateTime(timezone=True), onupdate=func.now())
def __str__(self):
return self.unit_id
@classmethod
def find_by_unit_id(cls, unit_id):
return cls.query.filter_by(unit_id=unit_id).first()
admin.add_view(ModelView(Unit, db.session))
class UnitSchema(marshmallow.ModelSchema):
id = field_for(Unit, 'unit_id', load_only=True)
created_at = field_for(Unit, 'created_at', load_only=True)
last_updated = field_for(Unit, 'last_updated', load_only=True)
class Meta:
model = Unit
unit_schema = UnitSchema()
units_schema = UnitSchema(many=True)
我想念什么?与其他查询一样,它按预期工作。
我们非常感谢您的帮助!
答案 0 :(得分:0)
我发现了错误:
result = units_schema.dumps(units).data
应为:
result = units_schema.dump(units).data # dump NOT dumps