我试图使用flask-marshmallow从一对多关系模型中将数据引入JSON,但是我被困在如何使用Nested在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)
答案 0 :(得分:0)
您必须在会话中提供烧瓶棉花糖。它使用棉花糖-sqlalchemy。该库使用会话基于primary_keys延迟加载关系。没有会话,您将仅获得ID列表。
您可以查看棉花糖-sqlalchemy docs here,以获取更多信息。
在您的示例中,您还定义了一个名为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