包含dict的sqlalchemy map对象

2024-04-26 13:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试绘制一个如下所示的对象:

    self.user = {lots of stuff in here}
    self.timeStamp = i am a date object
    self.coordinates  = {lots of stuff in here}
    self.tweet = {lots of stuff in here}

    self.favourite = 0
    self.reTweet = 0

非词典似乎很容易绘制

^{pr2}$

但是我不知道如何映射字典对象。理想情况下,这些物体应该有可能进入自己的表中,所以我们遵守第三范式。但是我不知道从哪里开始。有人能给我指出正确的方向吗?我应该把这些字典转换成自己的对象并映射它们吗?在

非常感谢


Tags: of对象inselfdate字典hereobject
2条回答

字典中有几个存储对象的选项:

  • 使用Text字段,通过json.dumps(value)将您的dict写入其中,使用json.loads(db_value)从中读取
  • 创建您自己的json type,就像这个线程中建议的那样:SQLAlchemy JSON as blob/text

    import jsonpickle
    import sqlalchemy.types as types
    
    class JsonType(types.MutableType, types.TypeDecorator):    
        impl = types.Unicode
    
        def process_bind_param(self, value, engine):
            return unicode(jsonpickle.encode(value))
    
        def process_result_value(self, value, engine):
            if value:
                return jsonpickle.decode(value)
            else:
                # default can also be a list
                return {}
    

而且,仅供参考,您很难遵循第三种标准格式,因为tweet对象没有严格定义的模式—将其存储在数据库字段中就可以了。在

顺便说一句,我发现使用mongodb存储tweet非常方便,因为它是无模式的,并且存储json对象。在

希望有帮助。在

用户和坐标条目可以存储为单独的表,tweet表将作为外键链接到该表。比如:

class Tweet(Base):
    __tablename__ = 'tweet'
    id = Column(Integer, Sequence('tweet_id_seq'), primary_key=True)
    user = Column(Integer, ForeignKey('user.id'))
    coords = Column(Integer, ForeignKey('coordinates.id'))
    timeStamp = Column(DateTime)
    favourite = Column(Integer)
    reTweet = Column(Integer)

class Coordinates(Base):
    __tablename__ = 'coordinates'
    id = Column(Integer, Sequence('coordinates_id_seq'), primary_key=True)
    lat = ...
    long = ...

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = ...

相关问题 更多 >