棉花糖结果定制 [英] Marshmallow result customization

查看:58
本文介绍了棉花糖结果定制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 jsonb 字段和棉花糖模式的 sqlalchemy 模型:

I have the sqlalchemy model with jsonb field and marshmallow schema for this model:

class Settings(db.Model):
    id = db.Column(UUID, primary_key=True,
                   server_default=text("uuid_generate_v4()"))
    settings = db.Column(JSONB)

class SettingsSchema(ma.ModelSchema):
    class Meta:
        model = Settings

我在 json 中序列化它,例如:

I'm serializing it in json like:

settings = Settings(settings={'qwerty': 'test'})
settings_schema = SettingsSchema(many=False, exclude=('id', ))
body = settings_schema.dump(settings).data

模型的 json 视图如下所示:

and json view of the model looks like this:

{
  "settings": {
    "qwerty": "test"
  }
}

当我将此模式用作嵌套时,结果如下

When I'm using this schema as nested I have result like

{
    "id": 123456,
    "some_field": "some_field_value",
    "other_field": "other_field_value",
    "settings": {
        "settings": {
            "qwerty": "test"
        }
    }
}

这个settings.settings"看起来很难看.

and this "settings.settings" looks ugly.

有没有办法告诉棉花糖我只需要将值作为转储结果,我的意思是

Is there a way said to marshmallow that I need only value as dump result, I mean

{
    "qwerty": "test"
}

可能我需要对元类做一些事情,但我不知道该怎么做.

Probably I need to do something with metaclasses, but I have no idea what should I do.

推荐答案

我知道了.我应该在我的架构中使用@post_dump:

I've got it. I should been used @post_dump in my schema:

class SettingsSchema(ma.ModelSchema):

    class Meta:
        model = WorkspaceSettings

    @post_dump(pass_many=True)
    def unwrap_settings(self, data, many):

        if many:
            return [item['settings'] or {} for item in data]
        else:
            return data['settings'] or {}

这篇关于棉花糖结果定制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆