我正在使用flask-marshmallow和flask-sqlalchemy,并且我想序列化一个包含Numeric字段的数据集,所有值都具有小数位,即2.5,但是当棉花糖将其转储到json时,它将截断小数位(将2.5更改为2)我在哪里出错?
ma.py
from flask_marshmallow import Marshmallow
ma = Marshmallow()
app.py
import ma
import db
from flask_restful import Api
.....
api = Api(app)
api.add_resource(LookupActivities, '/lookup_activity_by_type/<string:activity_type>')
if __name__ == "__main__":
db.init_app(app)
ma.init_app(app)
app.run(port=5000, debug=True)
model / lookup.py
from db import db
class LookupModel(db.Model):
__tablename__ = "asmirt_cpd_point_lookup"
__table_args__ = {"schema": "radcpd"}
asmirt_activity_id = db.Column(db.Integer, primary_key=True)
activity_type = db.Column(db.String(255))
activity = db.Column(db.String(255))
alt_text = db.Column(db.String(255))
activity_points = db.Column(db.Integer)
per_unit = db.Column(db.String(255))
@classmethod
def find_by_activity_type(cls, activity_type: str):
return cls.query.filter_by(activity_type=activity_type).all()
schema / lookup.py
from ma import ma
from models.lookup import LookupModel
class LookupSchema(ma.ModelSchema):
class Meta:
model = LookupModel
dump_only = ("asmirt_activity_id",)
resource / lookup.py
from flask_restful import Resource
from models.lookup import LookupModel
from schemas.lookup import LookupSchema
from flask_jwt_extended import jwt_required
from flask import jsonify
class LookupActivities(Resource):
@classmethod
def get(cls, activity_type):
data = LookupModel.find_by_activity_type(activity_type=activity_type)
print(data)
print(data[1].activity)
if data:
return {"activities": lookup_schema_list.dump(data)}, 200
return {'message', 'No activities in that group'}
在此示例中,它将更改数据库中的值2.5,但输出2。在其他示例中,我将收到错误消息“对象小数不可序列化”。有谁知道是什么原因造成的以及如何解决?
答案 0 :(得分:1)
您的模型列没有十进制声明。我猜您正在尝试从声明的整数列中插入十进制数据或从中获取十进制数据。尝试将列声明为十进制。
答案 1 :(得分:1)
在您的ma.ModelSchema
类中,您需要像这样覆盖十进制值:
from flask_marshmallow.fields import fields
class LookupSchema(ma.ModelSchema):
per_unit = fields.Float()
class Meta:
model = LookupModel
dump_only = ("asmirt_activity_id",)
现在您可以序列化per_unit
属性。对所有属性重复此操作。您可以使用Decimal
代替Float
。
不要忘记:在您的db.model
中,per_unit
必须是Float,例如:per_unit = db.Column(db.Float())