棉花糖-添加参数以包括子实体



我有一个名为Store的数据库模型,它与Products有关系。还定义了一个运行良好的StoreSchema。使用dump方法时,我可以检索商店及其产品。

现在,我不想带走产品,但可以选择,传递某种参数,但找不到简单的解决方案。我是否需要创建第二个不包括产品的StoreSchema,或者我可以更改它以涵盖这两种行为?

这是当前的代码

from marshmallow import fields
from app import db, ma
from app.models.product import ProductSchema

class Store(db.Model):
__tablename__ = "stores"
id = db.Column(db.Integer, primary_key=True)
public_id = db.Column(db.String(50), unique=True)
affiliate_code = db.Column(db.String(255), nullable=True)
url = db.Column(db.String(255), nullable=False)
name = db.Column(db.String(100), nullable=False)
country = db.Column(db.CHAR(2), nullable=False)
status = db.Column(db.String(100), nullable=False)
products = db.relationship("Product", backref="store", lazy='dynamic')
def serialize(self):
return StoreSchema().dump(self)

class StoreSchema(ma.SQLAlchemyAutoSchema):
products = fields.List(fields.Nested(ProductSchema, exclude=['id']))
class Meta:
exclude = ['id']
model = Store
load_instance = True

您可以在实例化时排除产品:

schema = StoreSchema(exclude=("products", ))

这里传递的列表与作为CCD_ 2属性传递的CCD_;id";。

最新更新