【发布时间】:2021-11-22 17:09:56
【问题描述】:
过去几天我一直在学习如何使用棉花糖模式序列化嵌套的 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)会返回以下内容
{
"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"]
}
如果有人知道有什么方法可以很好地实现这一点,我不确定是否有办法在模式中添加更多详细信息自定义序列化 - 但任何指针都将不胜感激!
【问题讨论】:
标签: python flask serialization sqlalchemy marshmallow