Flask Sqlalchemy 和 Marshmallow return 像“[Array]”这样的引号中的数组
Flask Sqlalchemy and Marshmallow return Array in Quotes like "[Array]“
我需要你的帮助
当我想 return 来自我的带有 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)
我错过了什么?对于其他查询,它按预期工作。
非常感谢任何帮助!
我发现错误:
result = units_schema.dumps(units).data
应该是:
result = units_schema.dump(units).data # dump NOT dumps
我需要你的帮助
当我想 return 来自我的带有 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)
我错过了什么?对于其他查询,它按预期工作。
非常感谢任何帮助!
我发现错误:
result = units_schema.dumps(units).data
应该是:
result = units_schema.dump(units).data # dump NOT dumps