Creating JSON type Column in SQLite with sqlalchemy

后端 未结 3 1209
日久生厌
日久生厌 2020-12-06 06:53

Is it possible to create JSON type Column in SQLite with sqlalchemy? I\'ve tried

import sqlalchemy.types as types
...
myColumn = Column(types.JSON())
         


        
相关标签:
3条回答
  • 2020-12-06 07:11

    JSON was not added to SQLite until version 3.9. You'll either need to upgrade your SQLite or convert your json to a string and save it as such, while converting it back to a json object when you pull it out.

    0 讨论(0)
  • 2020-12-06 07:17

    SQLAlchemy 1.3 will include support for SQLite JSON extension, so don't forget to upgrade:

    pip install --user -U --pre SQLAlchemy
    

    The dialect specific type sqlite.JSON implements JSON member access, usable through the base type types.JSON as well.

    0 讨论(0)
  • 2020-12-06 07:27

    My solution is:

    import json
    from sqlalchemy import TypeDecorator, types
    
    class Json(TypeDecorator):
    
        @property
        def python_type(self):
            return object
    
        impl = types.String
    
        def process_bind_param(self, value, dialect):
            return json.dumps(value)
    
        def process_literal_param(self, value, dialect):
            return value
    
        def process_result_value(self, value, dialect):
            try:
                return json.loads(value)
            except (ValueError, TypeError):
                return None
    
    ...
    
    myColumn = Column("name", Json)
    

    For more information: TypeDecorator

    0 讨论(0)
提交回复
热议问题