【问题标题】:Select object given identifier in Marshmallow在棉花糖中选择给定标识符的对象
【发布时间】:2021-10-08 14:58:24
【问题描述】:

我对 Marshmallow 包比较陌生,我正在尝试完成以下通过示例更好地解释的事情。

假设我们有以下对象:

data = {
    artists: [
       {
           id: 42,
           name: "Foo"
       },
       {
           id: 43,
           name: "Hector"
       }
   ],
   albums: [
       {
          name: "The Bar",
          artist: 42
       }

   ]
}

还有以下架构:

class ArtistSchema(Schema):
    id = fields.Int()
    name = fields.Str()

class AlbumSchema():
    name = fields.Str()
    artist = <see below>

有没有什么办法,当我使用 Marshmallow 加载我的数据时,我可以将 AlbumSchema 中的艺术家设置为与给定 id 对应的艺术家对象?目前我遍历艺术家,但我想知道是否有更聪明的方法来使用 Marshmallow。

【问题讨论】:

    标签: python nested marshmallow


    【解决方案1】:

    你可以的

    artist = fields.Nested(ArtistSchema)
    

    详情请见https://marshmallow.readthedocs.io/en/stable/nesting.html

    通常,ORM 通常支持外键,因此您不需要做太多工作来设置它们。

    【讨论】:

    • 这不起作用,因为我没有直接嵌套 ArtistSchema 对象
    猜你喜欢
    • 2016-08-01
    • 1970-01-01
    • 2019-01-29
    • 2022-11-04
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    相关资源
    最近更新 更多