python-3.xflask-sqlalchemymarshmallowflask-marshmallowmarshmallow-sqlalchemy

Scalarize a nested field using marshmallow


I have two Database Models like this

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')

When I serialize the model SettingsContainer using the following schemas

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'
        )

What I get is

[
    {
        "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'
            },
]

But I want to get data in the format of

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

I want to able to extract the Nested fields, I don't understand how to do it using the ma.Function method, thanks a lot to everyone in advance.


Solution

  • Okay so I found out the answer, what I have to do is to use ma.Function with ma.Pluck

    The appropriate serializers are.

    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'
            )