graphene-sqlalchemy icon indicating copy to clipboard operation
graphene-sqlalchemy copied to clipboard

Having issues with sqlalchemy_utils JSONType while reading

Open kavink opened this issue 8 years ago • 1 comments

I am using : https://github.com/kvesteri/sqlalchemy-utils

just so that I dont need to worry if I using Postgres in production or sqlite in dev environment .But from looks like it, I have no issues inserting data in json column, But when I read , seems like I get back a string, Wondering how to I get a python dict or json back when I read the column ?

from sqlalchemy_utils import JSONType
class Test(db.Model):
    __tablename__ = 'test'
    id = Column(Integer, primary_key=True)
    json = Column(JSONType)

What I see

"json": "{\"data\": .....

kavink avatar Oct 20 '17 20:10 kavink

This is the default behaviour of graphene - it uses the graphene JSONString type to represent JSONType

If you want this field to be actual JSON in the graphql output, you'll have to write your own implementation of the sqlalchemy type -> graphene type conversion. We have a similar problem that we solved by doing:

from graphene.types.generic import GenericScalar
from graphene_sqlalchemy import converter
from sqlalchemy_utils.types.json import JSONType

@converter.convert_sqlalchemy_type.register(JSONType)
def convert_json_to_generic_scalar(type, column, registry=None):
    return GenericScalar(
        description=converter.get_column_doc(column),
        required=not (converter.is_column_nullable(column)))

Not sure if this is the ideal or correct solution for the problem, but for now it works for us on a product that is WIP.

fredrikhl avatar Jan 17 '19 09:01 fredrikhl