2

Join returns just an ID value rather than the actual data.

Relationship: 1 to Many = Client : PaymentHistory

Issue: payment_history property is just 1, 2, 3 which is the ID of PaymentHistoy

Expected Result: payment_history must contain actual data instead of ID value

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

output

{
    "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
        }
    ]
}
Vinay
  • 548
  • 2
  • 12
  • Does the result change using [`joinedload()`](https://docs.sqlalchemy.org/en/13/orm/loading_relationships.html#sqlalchemy.orm.joinedload) instead of `join()`? – djnz Jun 14 '19 at 03:54
  • db.session.query(Client).options(joinedload(Client.payment_history)).all() returns the same result. – Vinay Jun 14 '19 at 06:08
  • Prolly related to how `ClientSchema` is defined. – Ilja Everilä Jun 14 '19 at 15:17
  • @IljaEverilä I have just added find the ClientSchema before the output section. I am using Flask Marshmallow serializer here. https://flask-marshmallow.readthedocs.io/en/latest/ – Vinay Jun 14 '19 at 19:16
  • [This thread solved my problem with Nested schemas](https://stackoverflow.com/questions/41858807/flask-marshmallow-sqlalchemy-serializing-many-to-many-relationships) – Vinay Jun 21 '19 at 05:18

0 Answers0