如何使用其值替换外键来构造API端点?

时间:2016-09-19 20:00:10

标签: flask flask-sqlalchemy api-design marshmallow

我目前正在使用Flask,SQLAlchemy和Marshmallow构建API。我有一个相当简单的DB模型:

class Transaction(db.Model):
    #Transaction Model
    __tablename__ = 'transactions'
    id = db.Column(db.Integer, primary_key = True)
    created_at = db.Column(db.DateTime, default=datetime.datetime.now)
    date = db.Column(db.DateTime)
    description = db.Column(db.Text)
    amount = db.Column(db.Float)
    category_id = db.Column(db.Integer, db.ForeignKey('categories.id'))
    category = db.relationship('Category', uselist=False, lazy='select')
    sub_category_id = db.Column(db.Integer, db.ForeignKey('sub_categories.id'))
    sub_category = db.relationship('SubCategory', uselist=False, lazy='select')
    account = db.Column(db.Integer, db.ForeignKey('accounts.id'))
    inner_transfer = db.Column(db.Boolean)



class Category(db.Model):
    __tablename__ = 'categories'
    id = db.Column(db.Integer, primary_key = True)
    category = db.Column(db.String(64), unique = True)
    transaction = db.relationship('Transaction')

My Marshmallow Schema如下所示:

class CategorySchema(ma.ModelSchema):
    class Meta:
        model = Category


category_schema = CategorySchema()
categories_schema = CategorySchema(many=True)

class TransactionSchema(ma.ModelSchema):
    class Meta:
        model = Transaction
        include_fk = True

一个非常简单的API端点:

@api.route('/transactions', methods=['GET'])
def transactions():
    all_transactions = Transaction.query.all()
    for transaction in all_transactions:
        transaction.category = Category.query.filter_by(id=transaction.category_id).first()
        print(transaction.category)
    items, errors = transactions_schema.dump(all_transactions)
    return jsonify(items)

我现在的问题:如何构建一个具有类别名称的JSON响应,而不是它的主键?我在所有交易中尝试了"进行交易" bit和print语句中我得到了类别名称,但它没有显示在我的JSON响应中......

我不完全确定如何编写数据库模型。我特别坚持的是db.relationship。在我的Transaction类中声明它似乎没有帮助,因为它只显示Category类的主键。我上下阅读了Flask-SQLAlchemy文档,但我一无所知。

非常感谢任何帮助和指示!

谢谢!

1 个答案:

答案 0 :(得分:2)

我创建了一个简单版本的模型来显示这个实际操作,并为数据库播种了两个测试记录:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
ma = Marshmallow(app)

# DB Models
class Transaction(db.Model):
    #Transaction Model
    __tablename__ = 'transactions'
    id = db.Column(db.Integer, primary_key = True)
    category_id = db.Column(db.Integer, db.ForeignKey('categories.id'))
    category = db.relationship('Category', uselist=False, lazy='select')

class Category(db.Model):
    __tablename__ = 'categories'
    id = db.Column(db.Integer, primary_key = True)
    category = db.Column(db.String(64), unique = True)
    transaction = db.relationship('Transaction')

# Schema
class TransactionSchema(ma.ModelSchema):
    class Meta:
        model = Transaction
        include_fk = True
    # Here is the function, you do not not need to define all fields you want to dump
    category_name = ma.Function(lambda obj: obj.category.category)

然后打电话: TransactionSchema(many=True).dump(Transaction.query.all()).data

收率: [{u'category': 1, u'category_id': 1, u'category_name': u'Test1', u'id': 1}, {u'category': 2, u'category_id': 2, u'category_name': u'Test2', u'id': 2}]

也可以使用功能覆盖您的字段并仅将其转储:

class TransactionSchema(ma.ModelSchema):
class Meta:
    model = Transaction
    include_fk = True
category = ma.Function(lambda obj: obj.category.category, dump_only=True)

收率: [{u'category': u'Test1', u'category_id': 1, u'id': 1}, {u'category': u'Test2', u'category_id': 2, u'id': 2}]