0

我有两个这样的数据库模型

class Setting(db.Model):
    id = db.Column(db.Integer, id=True)
    container_id = ST_db.Column(ST_db.Integer, db.ForeignKey('settings_container.id'))
    setting_name = ST_db.Column(ST_db.String(50))
    setting_value = ST_db.Column(ST_db.String(50))

class SettingsContainer(db.Model):
    id = db.Column(db.Integer, id=True)
    settings = db.relationship('Settings', backref='container', cascade='all, delete')

当我使用以下模式序列化模型SettingsContainer

class Setting(ma.Schema):
    class Meta:
        fields = (
            'setting_name',
            'setting_value',
        )

class SettingsContainer(ma.Schema):
    settings = ST_ma.Nested(Setting, many=True)
    class Meta:
        fields = (
            'id',
            'settings'
        )

我得到的是

[
    {
        "id": 1
        "settings": [
            {
                "setting_name": 'name1',
                "setting_value": 'value1'
            },
            {
                "setting_name": 'name2',
                "setting_value": 'value2'
            },
    }
        "id": 2
        "settings": [
            {
                "setting_name": 'name3',
                "setting_value": 'value3'
            },
            {
                "setting_name": 'name4',
                "setting_value": 'value4'
            },
]

但我想以以下格式获取数据

[
   {
       "id": 1
       "settings": [['name1', 'value1'], ['name2', 'value2']]
   }
   {
       "id": 2
       "settings": [['name3', 'value3'], ['name4', 'value4']]
   }
]

我希望能够提取嵌套字段,我不明白如何使用该ma.Function方法,提前非常感谢大家。

4

1 回答 1

0

好的,所以我找到了答案,我要做的就是使用ma.Functionwithma.Pluck

适当的序列化程序是。

class Setting(ma.Schema):
    complete_setting = ma.Function(lambda setting:(
        setting.setting_name,
        setting.setting_value,
    )) 

class SettingsContainer(ma.Schema):
    settings = ma.List(ma.Pluck(Setting, 'complete_setting'))
    class Meta:
        fields = (
            'id',
            'settings'
        )
于 2020-10-30T04:54:12.090 回答