声明式SQLAlchemy中的标记词典?

问题描述:

我的工作已经使用sqlalchemy.ext.declarative实施了相当大的代码库,我需要一个类似字典的属性添加到类之一。我需要的是与this question相同,但以声明方式。有更多SQLAlchemy知识的人能给我一个例子吗? 在此先感谢...声明式SQLAlchemy中的标记词典?

+0

如果你不需要查询属性,那么这个答案提供了一种替代方法:http://*.com/questions/1378325/python-dicts-in-sqlalchemy/1378818#1378818 – 2009-09-09 18:45:48

声明是确定的事情的另一种方式。事实上,如果你使用分离的映射,你会得到完全相同的环境。

因为我回答了另一个问题,我会尝试这一个也。希望它让更多upvotes;)

嗯,首先我们定义的类

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 

我得到:

​​

现在,让我们检查笔记表...

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

我得到:

1 color orange 
1 data none 
1 size big 

它的作品! :D

+0

谢谢@nosklo! – 2009-09-10 10:01:42

+0

我得到一个'sqlalchemy.exceptions.NoReferencedTableError:找不到表“项目”,用以生成异物key' – 2009-09-10 11:17:12

+0

定了!不得不从'Note.id_item'除去'ForeignKey的( 'items.id')'和添加'注意.__表__。append_constraint(ForeignKeyConstraint([ 'id_item'],[ 'items.id']))'的声明之后'Item'。还必须用'Item._notesdict'中的'Note .__ table __.c.name'替换'Note.name'。 – 2009-09-10 16:10:45