Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

serializing of a Related column #333

Open
bbbart opened this issue Aug 3, 2020 · 2 comments
Open

serializing of a Related column #333

bbbart opened this issue Aug 3, 2020 · 2 comments

Comments

@bbbart
Copy link

bbbart commented Aug 3, 2020

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 Models 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?

@VietHo
Copy link

VietHo commented Aug 8, 2020

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

@jsormaz
Copy link

jsormaz commented Oct 20, 2021

@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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants