我在棉花糖中有以下模式,这些模式依赖于用 sqlalchemy 构建的模型。我能够显示一个 API 响应,其中包含多个订阅价格,这些订阅价格来自名为“subscription_prices”的 Journal 模型的多对多关系。
from marshmallow import fields
class SubscriptionPriceSchema(ma.Schema):
price = fields.Decimal(as_string=True)
class Meta:
model = SubscriptionPrice
fields = (
"price",
"year",
)
class JournalSchema(ma.Schema):
subscription_prices = fields.Nested(SubscriptionPriceSchema, many=True)
class Meta:
model = Journal
fields = (
"title",
"subscription_prices"
)
但是,我想做的是添加一个名为“出处”的字段,该字段与订阅价格处于同一水平。所以我试图这样做,但它不起作用:
from marshmallow import fields
class SubscriptionPriceSchema(ma.Schema):
price = fields.Decimal(as_string=True)
class Meta:
model = SubscriptionPrice
fields = (
"price",
"year",
)
class SubscriptionSchema(ma.Schema):
provenance = fields.String(attribute="publisher.provenance")
subscription_prices = fields.Nested(SubscriptionPriceSchema, many=True)
class Meta:
fields = (
"provenance",
"subscription_prices",
)
class JournalSchema(ma.Schema):
subscription_prices = fields.Nested(SubscriptionSchema)
class Meta:
model = Journal
fields = (
"title",
"subscription_prices"
)
似乎关系 'subscription_prices' 没有传递超过一个级别,因此它没有达到新的 SubscriptionSchema。关于如何完成这项工作的任何想法?