SQLAlchemy示例:属性实体化建模

假设有这样的场景, 某实体在具体条目上, 其属性是不定的, 或者其属性是充分稀疏的:

idnameattr_0attr_1attr_2attr_n
1foo1abc33any

这种情况下, 把属性看成是单独的实体, 是一个更好的建模方式:

idname
1foo
identity_idattr_nameattr_value
11attr_01
21attr_133
n1attr_nany

这种模型下, ORM 层面我们考虑封装一个对操作更友好的上层操作接口, 比如:

1
2
3
4
5
obj = Entity()
obj['attr_0'] = '1'
obj['attr_1'] = '33'
session.add(obj)
session.commit()

实现上, 就是把对象的方法, 包装成 SQLAlchemyORM 中的对应的关系操作.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class BaseModel(declarative_base()):
__abstract__ = True

class Entity(BaseModel):
__tablename__ = 'entity'

id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(Unicode(32), server_default='')

_attributes = relationship('Attribute',
collection_class=attribute_mapped_collection('key'),
lazy='joined', cascade="all, delete-orphan")
attributes = association_proxy('_attributes', 'value',
creator=lambda k, v: Attribute(key=k, value=v))


class Attribute(BaseModel):
__tablename__ = 'attribute'

id = Column(Integer, autoincrement=True, primary_key=True)
entity = Column(Integer, ForeignKey('entity.id'), index=True)
key = Column(Unicode(32), server_default='')
value = Column(UnicodeText, server_default='')


if __name__ == '__main__':
BaseModel.metadata.create_all(Engine)

session = Session()

entity = Entity(name=u'哈哈')
entity.attributes[u'first'] = u'abc'
entity.attributes[u'sec'] = u'hoho'
session.add(entity)
session.commit()

entity = session.query(Entity).first()
print entity.attributes
del entity.attributes['first']
session.commit()

entity = session.query(Entity).first()
print entity.attributes

实现上就两点:

_attributes 关系中, 指定 collection_class, 于是就可以得到一个像 dict 的属性对象了.association_proxydict的属性对象中只抽出我们关心的 value 属性值.

这个场景中, 还可以再进一步, 在 Entity 类上实现 dict 的一些方法, 直接操作其 attributes 属性, association_proxy 就直接返回 Entity 的实例, 这样代码可以变成这样:

1
2
3
entity = Entity(name=u'ABC')
entity[u'first'] = u'a'
entity[u'sec'] = u'hoho'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值