Skip to content

Error dumping objects with JSONB fields (with already dumped date/datetime data) #24

@mahenzon

Description

@mahenzon

If you have a model with JSONB field, and there's a dumped date / datetime, marshmallow won't be able to serialize it due to it being serialized already (date and datetime strings will cause an error when tried to serialize)
smth like TypeError: descriptor 'isoformat' requires a 'datetime.date' object but received a 'str'

possible solution: load all JSONB fields when loading object, or just before serializing

from marshmallow import Schema, fields
from sqlalchemy.dialects.postgresql import JSONB


def load_jsonb_columns(instance, schema: Schema) -> None:
    """
    :param instance:
    :param schema:
    :return:
    """
    for attr in type(instance)._sa_class_manager.attributes:
        if not isinstance(attr.expression.type, JSONB):
            continue

        if hasattr(instance, attr.name) and attr.name in schema.declared_fields:
            fld: fields.Nested = schema.declared_fields[attr.name]
            if not isinstance(fld, fields.Nested):
                continue
            deserialized = fld.schema.load(getattr(instance, attr.name))
            setattr(instance, attr.name, deserialized)

also there can be other types which require to be converted

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions