SQLAlchemy-Marshmallow 如何将嵌套模式对象序列化为值列表

SQLAlchemy-Marshmallow how to serialize nested schema objects as a list of values

过去几天我一直在学习如何使用棉花糖模式序列化嵌套的 SQLAlchemy 关系模型,但是,我找不到实现我想要的结果的方法。

到目前为止,我已经能够使用以下模型和架构获得多对多关系来打印所有级别

class RecipeIngredient(db.Model):
    __tablename__ = 'recipe_ingredient'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    recipe_id = db.Column(db.Integer, db.ForeignKey('recipe.id'))
    ingredient_name = db.Column(db.String(64), db.ForeignKey('ingredient.name'))


class Recipe(db.Model):
    __tablename__ = 'recipe'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(64))
    desc = db.Column(db.String(256))
    ingredients = relationship("Ingredient", secondary="recipe_ingredient", backref="recipes")


class Ingredient(db.Model):
    __tablename__ = 'ingredient'
    name = db.Column(db.String(64), primary_key=True)


class RecipeSchema(Schema):
    class Meta:
        ordered = True

    id = fields.Int()
    title = fields.Str()
    desc = fields.Str()
    ingredients = fields.Nested('IngredientSchema', exclude=('recipes',), many=True)


class IngredientSchema(Schema):
    class Meta:
        ordered = True

    name = fields.Str()
    recipes = fields.Nested('RecipeSchema', exclude=('categories',), many=True)

执行 RecipeSchema().dump(recipe) 将 return 以下

{
    "id": 1,
    "title": "Pancakes",
    "desc": "Tastes just like a yorkshire pudding!",
    "ingredients": [
      {
        "name": "Milk"
      },
      {
        "name": "Egg"
      },
      {
        "name": "Flour"
      }
    ]
  }

但是,我正在尝试让 ingredients 等嵌套属性显示在仅包含值的列表中,例如

{
    "id": 1,
    "title": "Pancakes",
    "desc": "Tastes just like a yorkshire pudding!",
    "ingredients": ["Milk", "Egg", "Flour"]
}

如果有人知道实现此目的的任何方法,那将是很棒的,我不确定是否有在模式中添加更多详细信息自定义序列化的方法 - 但任何指针将不胜感激!

哦,我明白了,它涉及创建自定义字段 class,如文档 here 中所述。

class IngredientName(fields.Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if value is None:
            return ''
        return value.name

然后我在食谱架构中使用了这个 class 和以下行

ingredients = fields.List(IngredientName(), exclude=('recipes',), many=True)