marshmallow-sqlalchemy
marshmallow-sqlalchemy copied to clipboard
serializing of a Related column
As far as I can interpret the code correctly, I believe that there is no serialising happening at all for columns provided to a Related
field.
From class Related(fields.Field):
def _serialize(self, value, attr, obj):
ret = {prop.key: getattr(value, prop.key, None) for prop in self.related_keys}
return ret if len(ret) > 1 else list(ret.values())[0]
In my case (a REST API built with Flask) this results in Object of type furl is not JSON serializable
, as I'm referring to a related model with a sqlalchemy_utils.URLType
column, which doesn't return a str
but an object from the type furl
.
The blind getattr
in the code above should be some kind of serialisation instead.
I don't see an easy way of solving this, as of course, the SQLAlchemyAutoSchema
refers to the underlying Model
s to get information about the Related
columns, and doesn't know about any Marshmallow Schema
related to that other Model
.
However, is there a way to force an actual (and correct) serialization of these values?
I think I'm having a related issue, when using SQLAlchemyAutoSchema include_relationships = True
I am getting TypeError: Object of type UUID is not JSON serializable
with postgres uuid.
I'm fixing by adding
from json import JSONEncoder
from uuid import UUID
def jsonEncoderDefault(self, o):
if isinstance(o, UUID):
return str(o)
return JSONEncoder.default(self, o)
JSONEncoder.default = jsonEncoderDefault
But I was not having that issue when using ModelSchema
@VietHo I am having the same issue.
Your solution almost works, Except now I am getting a recursion error:
if isinstance(o, UUID): RecursionError: maximum recursion depth exceeded while calling a Python object
This wasn't an issue when I was using integers as the primary key.
I'm about to start storing the UUID's as strings in the database.
Any ideas?