0

i trying to use flask-marshmallow to bring data to JSON from one-to-many relationships model but i'm stuck how to use Nested to display in the details all th data from db.relationships. Now it only list with numbers. Here how it looks now. Please pay attention to the last item (invoice_add). Many thanks for your explanations.

Not the output look like shown below

['id': 1, 'invoice_actual_payment': [], 'invoice_date': None, 'path': None, 'invoice_add': [1, 2]}]

Need to looks

'id': 1, 'invoice_actual_payment': [], 'invoice_date': None, 'path': None, 'invoice_add': [{'id': 1, 'addDescription': 'addPickUp'}, {'id': 2, 'addDescription': 'addPickUp'}]}]

My models are:

class Invoicecust(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    fin_id = db.Column(db.Integer)
    path = db.Column(db.Text)
    prefin_id = db.Column(db.Integer, db.ForeignKey('prefin.id'))
    req_id = db.Column(db.Integer, db.ForeignKey('request.id'))
    invoice_number = db.Column(db.Text)
    invoice_amount = db.Column(db.Float)
    invoice_vat = db.Column(db.Float)
    invoice_date = db.Column(db.DateTime)
    invoice_deadline_payment = db.Column(db.DateTime)
    invoice_tracking_number = db.Column(db.Text)
    invoice_tracking_company = db.Column(db.Text)
    invoice_tracking_day = db.Column(db.DateTime)
    invoice_actual_payment = db.relationship('Invoice_payment_c', backref='inv_c', lazy='dynamic')
    invoice_add = db.relationship('AddInvoiceCust', backref='inv_add')
    customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'))

class AddInvoiceCust(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    addNumber = db.Column(db.Integer)
    addDescription = db.Column(db.Text)
    addAmount=db.Column(db.Float)
    addVat = db.Column(db.Float)
    invoicecust_id = db.Column(db.Integer, db.ForeignKey('invoicecust.id') )

My Shema are:

class InvoicecustShema(ma.ModelSchema):
    class Meta:
        model = Invoicecust

class AddInvoiceShema(ma.ModelSchema):
    class Meta:
        model=AddInvoiceCust
        fields = ('id', 'addDescription' , 'test' )
    test=fields.Nested(InvoicecustShema)
dmitriy_one
  • 477
  • 1
  • 5
  • 16

1 Answers1

0

You have to supply flask-marshmallow your session. It uses marshmallow-sqlalchemy. This library uses the session to lazy load relationships based on the primary_keys. Without the session you will only get a list of id's.

You can check out the marshmallow-sqlalchemy docs here for more information.

In your example you also have a field defined called test.

class AddInvoiceShema(ma.ModelSchema):
    class Meta:
        model=AddInvoiceCust
        fields = ('id', 'addDescription' , 'test' )
    test=fields.Nested(InvoicecustShema)

The field should be named after the relationship like so:

class AddInvoiceShema(ma.ModelSchema):
    invoice_add = fields.Nested(InvoicecustShema, many=True)

    class Meta:
        model=AddInvoiceCust
        session=db.session
Lucas Scott
  • 455
  • 3
  • 10