如何使用postgres与sql alchemy进行连接查询

时间:2017-11-05 05:30:36

标签: postgresql sqlalchemy flask-sqlalchemy

ExpenseList表有两个外键,我想从这个类别中获取相应类别的费用列表。目前,只有在我应用以下查询时才会返回category_id:

query = ExpenseList.query.filter_by(user_id=6)
return make_response(jsonify([i.serialize for i in query.all()])),200

它的回复响应如下:

[
{
    "category": 3,
    "created_on": "Sun, 05 Nov 2017 09:40:19 GMT",
    "money_spent": "50",
    "name": "DVD"
},
{
    "category": 3,
    "created_on": "Sun, 05 Nov 2017 09:40:39 GMT",
    "money_spent": "100",
    "name": "Movie"
}
]

模型架构是

class ExpenseList(db.Model):
    __tablename__ = 'expense_list'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(500), unique=True, nullable=False)
    money_spent = db.Column(db.String(500), nullable=False)
    category_id = db.Column(db.Integer, db.ForeignKey('category_list.id'))
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    is_recurring = db.Column(db.Boolean,nullable=False, default=False)
    created_on = db.Column(db.DateTime, nullable=False)

    @property
    def serialize(self):
        return {
            'name' : self.name,
            'money_spent' : self.money_spent,
            'category' : self.category_id,
            'created_on' : self.created_on
         }


class CategoryList(db.Model):
    __tablename__ = 'category_list'

    id = db.Column(db.Integer,primary_key = True, autoincrement=True)
    name = db.Column(db.String(500), unique=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    created_on = db.Column(db.DateTime, nullable=False)

如何在响应对象中获取类别名称而不是category_id,我也尝试了backrefs,懒惰等,但不知道我哪里出错了。

1 个答案:

答案 0 :(得分:0)

这是您想要的加入

query(ExpenseList.name.label('expense_name'),
    ExpenseList.money_spent,
    CategoryList.name.label('category_name'),
    ExpenseList.created_on)\
.join(CategoryList, ExpenseList.category_id == CategoryList.id)\
.filter_by(ExpenseList.user_id=6)

以及您的CategoryList模型中令人担忧的部分是:

name = db.Column(db.String(500), unique=True, autoincrement=True)