marshmallow-sqlalchemy无法从父模型_schema获取子模型的数据

时间:2019-09-25 09:33:34

标签: flask sqlalchemy marshmallow

我正在尝试使用棉花糖sqlalchemy创建API

但是,当我转储数据时,它仅显示父模型数据

like {'id':1,'date':'2019-09-01'}

如何获取类似{'id':1,'date':'2019-09-01','orders':{'id':1,'date':'2019-09-01 '},{'id':1,'date':'2019-09-01'}}

模型是

class Order(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    company_id = db.Column(db.Integer, db.ForeignKey('user_company.id'), nullable=False)
    company = db.relationship('UserCompany', backref='orders', lazy=True)
    date = db.Column(db.DateTime(), server_default=func.now())

class UserCompany(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    company_name = db.Column(db.String(length=20))

架构是

class OrderSchema(ModelSchema):
    class Meta:
        sqla_session = db.Session
        fields = ('id', 'date')
        model = Order


order_schema = OrderSchema()
orders_schema = OrderSchema(many=True)


class UserCompanySchema(ModelSchema):
    orders = Nested(OrderSchema, many=True)
    class Meta:
        fields = ('id', 'company_name')
        model = UserCompany
        sqla_session = db.session


user_company_schema = UserCompanySchema()

视图是

company = UserCompany.query.get(current_user.company.id)
print(user_company_schema.dump(company))

{'id': 1, 'date': '2019-09-01'}

我想要的是

{'id': 1, 'date': '2019-09-01', 'orders': {'id': 1, 'date': '2019-09-01'}, {'id': 1, 'date': '2019-09-01'}}

1 个答案:

答案 0 :(得分:1)

如果希望它们出现在转储中,则需要在Meta类中显式设置所有期望的字段。

class UserCompanySchema(ModelSchema):
    orders = Nested(OrderSchema, many=True)
    class Meta:
        fields = ('id', 'company_name', 'orders')
        model = UserCompany
        sqla_session = db.session