2009-09-09 9 views
6

sqlalchemy.ext.declarativeを使用して実装された非常に大きなコードベースで作業しています。クラスの1つにdict-likeプロパティを追加する必要があります。私が必要とするのは、this questionと同じですが、宣言的な方法です。 SQLAlchemyの知識があれば誰でも私に例を挙げられますか? ありがとうございます...宣言的なSQLAlchemyのタグの辞書?

+0

プロパティをクエリする必要がない場合、この回答は代替アプローチを提供します:http://stackoverflow.com/questions/1378325/python-dicts-in-sqlalchemy/1378818#1378818 –

答えて

13

宣言は物事を定義する別の方法です。事実上、分離マッピングを使用した場合とまったく同じ環境で終了します。

私はもう1つの質問に答えたので、私もこれを試してみます。

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 

私が手::

​​

今聞かせての最初の私たちはクラスが

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() 

今度はテストを行いましょう定義、)

まあ、それはより多くのupvotesを与えるホープノートテーブルを確認してください...

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! –

+0

'sqlalchemy.exceptions.NoReferencedTableError:外部キーを生成するテーブル 'items'を見つけることができませんでした。 ' –

+0

これを修正しました! 'Note.id_item'から' ForeignKey( 'items.id') 'を削除して、' Note.__ table __。append_constraint(ForeignKeyConstraint(['id_item']、[items.id '])) 'を宣言の後に追加しなければならなかった'Item'。 'Note.name'を' Item._notesdict'の 'Note .__ table __。c.name'に置き換えなければなりません。 –

関連する問題