Flask SqlAlchemy Join仅返回一个ID值

时间:2019-06-14 03:08:14

标签: python postgresql flask sqlalchemy flask-sqlalchemy

联接只返回一个ID值,而不是实际数据。

关系:一对多=客户:PaymentHistory

问题: payment_history属性仅为1,2,3,这是PaymentHistoy的ID

预期结果: Payment_history必须包含实际数据而不是ID值

client_model.py

class Client(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    pending_amount = db.Column(db.Integer, nullable=False)
    invoices = db.relationship('Invoice', backref='client', lazy='select')
    payment_history = db.relationship('PaymentHistory',
                                      backref='client',
                                      lazy='select')

payment_history.py

class PaymentHistory(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    payment_mode = db.Column(db.String(100), nullable=False)
    amount = db.Column(db.Integer, nullable=False)
    client_id = db.Column(db.Integer,
                          db.ForeignKey('client.id'),
                          nullable=False)

route_handler.py

@client_blueprint.route('/get_all', methods=['POST'])
def get_all():
    cli = db.session.query(Client).join(PaymentHistory).all()
    clients = ClientSchema(many=True).dump(cli).data
    return jsonify({'clients': clients})

client_schema.py

class ClientSchema(ma.ModelSchema):
    class Meta:
        model = Client

输出

{
    "clients": [
        {
            "created_at": "2019-06-14T02:12:08.038526+00:00",
            "id": 1,
            "invoices": [],
            "payment_history": [
                1, 2, 3
            ],
            "pending_amount": 0,
            "updated_at": null
        }
    ]
}

0 个答案:

没有答案