声明性SQLAlchemy中的标签词典?

Mar*_*ech 6 python sqlalchemy declarative

我正在开发一个已经实现的相当大的代码库,sqlalchemy.ext.declarative我需要在其中一个类中添加类似dict的属性.我需要的是与这个问题相同,但是以声明的方式.在SQLAlchemy中有更多知识的人能给我一个例子吗?提前致谢...

nos*_*klo 13

声明只是定义事物的另一种方式.实际上,与使用分离映射完全相同的环境最终会得到完全相同的环境.

既然我回答了另一个问题,我也会尝试这个问题.希望它能提供更多的赞成;)

好吧,首先我们定义类

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()
Run Code Online (Sandbox Code Playgroud)

现在让我们做一个测试:

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
Run Code Online (Sandbox Code Playgroud)

我明白了:

{u'color': u'orange', u'data': u'none', u'size': u'big'}
Run Code Online (Sandbox Code Playgroud)

现在让我们查看笔记表......

for note in s.query(Note):
    print note.id_item, note.name, note.value
Run Code Online (Sandbox Code Playgroud)

我明白了:

1 color orange
1 data none
1 size big
Run Code Online (Sandbox Code Playgroud)

有用!!:d