在发送回响应之前将自定义字段添加到架构

时间:2019-07-03 01:03:52

标签: flask marshmallow flask-restplus

我正在使用flask_restplus作为我的API,并使用flask_marshmallow来序列化我的数据库模型。在向用户发送从数据库返回的结果的模式转储回给用户之前,我想添加一个新字段,其中包含amount列的总和。

// model.py
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from app import db, ma

class Income(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    amount = db.Column(db.Float)
    description = db.Column(db.String)
    frequency = db.Column(db.String)

    def __init__(self, amount, description, frequency):
        self.amount = amount
        self.description = description
        self.frequency = frequency

class IncomeSchema(ma.Schema):
    class Meta:
        fields = ('id', 'description', 'amount', 'frequency', '_total')
        ordered = True
    total = 0.0
routes.py
// routes.py
income_schema = IncomeSchema()

@ns.route('/')
class IncomeList(Resource):
    def get(self):
        income = Income.query.all()
        if income:
            total = float()
            for i in income:
                total += i.amount
            total = { 'total': total }
        income_schema.total = total # this isn't working
        return income_schema.dump(income).data, 201

我想在回复中添加一个total字段。

0 个答案:

没有答案