SQLAlchemy声明式的标签字典?

6 投票
1 回答
2035 浏览
提问于 2025-04-15 14:11

我正在处理一个比较大的代码库,这个代码库是用 sqlalchemy.ext.declarative 实现的。我需要在其中一个类里添加一个像字典一样的属性。我想要的效果和 这个问题 里说的一样,但我希望用声明式的方式来实现。有没有对 SQLAlchemy 更了解的人能给我一个例子呢?提前谢谢大家...

1 个回答

14

声明式编程就是另一种定义事物的方式。实际上,你得到的环境和使用分开的映射方式是完全一样的。

因为我回答了另一个问题,所以我也来试试这个。希望能得到更多的赞;)

首先,我们定义类:

from sqlalchemy import Column, Integer, String, Table, create_engine
from sqlalchemy import orm, MetaData, Column, ForeignKey
from sqlalchemy.orm import relation, mapper, sessionmaker
from sqlalchemy.orm.collections import column_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base(bind=engine)

class Note(Base):
    __tablename__ = 'notes'

    id_item = Column(Integer, ForeignKey('items.id'), primary_key=True)
    name = Column(String(20), primary_key=True)
    value = Column(String(100))

    def __init__(self, name, value):
        self.name = name
        self.value = value        

class Item(Base):
    __tablename__ = 'items'
    id = Column(Integer, primary_key=True)
    name = Column(String(20))
    description = Column(String(100))
    _notesdict = relation(Note, 
                          collection_class=column_mapped_collection(Note.name))
    notes = association_proxy('_notesdict', 'value', creator=Note)

    def __init__(self, name, description=''):
        self.name = name
        self.description = description

Base.metadata.create_all()

现在我们来做个测试:

Session = sessionmaker(bind=engine)
s = Session()

i = Item('ball', 'A round full ball')
i.notes['color'] = 'orange'
i.notes['size'] = 'big'
i.notes['data'] = 'none'

s.add(i)
s.commit()
print i.notes

我得到:

{u'color': u'orange', u'data': u'none', u'size': u'big'}

现在我们检查一下笔记表...

for note in s.query(Note):
    print note.id_item, note.name, note.value

我得到:

1 color orange
1 data none
1 size big

它工作了!! :D

撰写回答