后端会报错的代码:
# 商品管理Model的创建
class Goods(db.Model):
__tablename__ = 't_goods'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(512))
price = db.Column(db.DECIMAL(20,4)) # 这里使用db.DECIMAI(20,4),在获取商品列表时会报错 TypeError: Object of type Decimal is not JSON serializable
number = db.Column(db.Integer)
introduce = db.Column(db.Text)
big_log = db.Column(db.String(256))
small_log = db.Column(db.String(256))
state = db.Column(db.Integer) # 0 未通过 1 审核中 2 已审核
is_promote = db.Column(db.Integer)
hot_number = db.Column(db.Integer)
weight = db.Column(db.Integer)
cid_one = db.Column(db.Integer,db.ForeignKey('t_category.id'))
cid_two = db.Column(db.Integer,db.ForeignKey('t_category.id'))
cid_three = db.Column(db.Integer,db.ForeignKey('t_category.id'))
category = db.relationship('Category',foreign_keys=[cid_three])
def to_dict(self):
return {
'id':self.id,
'name':self.name,
'price':self.price,
'number':self.number,
'introduce':self.introduce,
'big_log':self.big_log,
'small_log':self.small_log,
'state':self.state,
'is_promote':self.is_promote,
'hot_number':self.hot_number,
'weight':self.weight,
'cid_one':self.cid_one,
'cid_two':self.cid_two,
'cid_three':self.cid_three,
'attrs':[a.to_dict() for a in self.category.attrs]
}
之所以price设置为decimal类型而不是float类型,是因为float会丢失精度,在涉及金额时一般设置为decimal类型