AdCombo / flask-combo-jsonapi

Flask REST JSON:API on steroids.
MIT License
32 stars 16 forks source link

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

Open mahenzon opened 4 years ago

mahenzon commented 4 years ago

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

rexdivakar commented 4 years ago

Assign it to me i will work on it @mahenzon

mahenzon commented 4 years ago

@rexdivakar cool! Good luck Please don't forget to provide tests 🙂

mahenzon commented 4 years ago

plz note that modifying object in-place may (and will) cause an error when session is flushed, because JSONB attrs will contain unserializable values. Please consider not modifying real object implicitly

mahenzon commented 3 years ago

@rexdivakar any news?

rexdivakar commented 3 years ago

Hey @mahenzon Its been a while and I missed this issue, will work on it and raise a PR soon