代码之家  ›  专栏  ›  技术社区  ›  George Mauer

如何使SQLAlchemy将对象存储为json而不是关系?

  •  0
  • George Mauer  · 技术社区  · 6 年前

    我有两节课

    class PersonName:
       Salutation: String
       FirstName : String
       LastName : String
    

    class Person:
      id : Integer
      Name : PersonName   
      ...other props...
    

    PersonName 我希望SQLAlchemy只使用一个字符串列并将实例序列化为JSON(并在获取实例时反序列化)。我不需要深入的查询或任何东西,只需要基本的序列化。

    这可能吗?

    0 回复  |  直到 6 年前
        1
  •  0
  •   SergeyR    5 年前

    Here 是个不错的解决方案。

    定义类如下:

    class Person(db.Model):
        __tablename__ = 'persons'
        id = db.Column(db.Integer, primary_key=True)
        fancy_name = db.Column(JsonEncodedDict)
    

    像这样使用:

    person = Person(fancy_name={'Salutation': 'Mr.', 'FirstName': 'Sergey', 'FullMiddleName': 'Vladimirovich'})
    

    import json
    from sqlalchemy.ext import mutable
    
    db = SQLAlchemy()
    
    class JsonEncodedDict(db.TypeDecorator):
        """Enables JSON storage by encoding and decoding on the fly."""
        impl = db.Text
    
        def process_bind_param(self, value, dialect):
            if value is None:
                return '{}'
            else:
                return json.dumps(value)
    
        def process_result_value(self, value, dialect):
            if value is None:
                return {}
            else:
                return json.loads(value)
    
    
    mutable.MutableDict.associate_with(JsonEncodedDict)