0

我试图使用flask-marshmallow将数据从一对多关系模型带到JSON,但我被困在如何使用嵌套来详细显示来自db.relationships的所有数据。现在它只列出数字。现在看起来如何。请注意最后一项(invoice_add)。非常感谢您的解释。

不是输出如下所示

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

需要看

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

我的模型是:

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') )

我的Shema是:

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

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

1 回答 1

0

您必须提供 flask-marshmallow 您的会话。它使用棉花糖-sqlalchemy。该库使用会话基于 primary_keys 延迟加载关系。如果没有会话,您只会得到一个 id 列表。

您可以在此处查看 marshmallow-sqlalchemy文档以获取更多信息。

在您的示例中,您还定义了一个名为test.

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

该字段应以如下关系命名:

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

    class Meta:
        model=AddInvoiceCust
        session=db.session
于 2020-01-02T14:32:00.923 回答