【问题标题】:Dictionary of tags in declarative SQLAlchemy?声明性 SQLAlchemy 中的标签字典?
【发布时间】:2009-09-09 15:54:37
【问题描述】:

我正在编写一个使用sqlalchemy.ext.declarative 实现的相当大的代码库,我需要向其中一个类添加一个类似dict 的属性。我需要的和this question 中的一样,但是是声明式的。有更多 SQLAlchemy 知识的人可以举个例子吗? 提前谢谢...

【问题讨论】:

标签: python sqlalchemy declarative


【解决方案1】:

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

既然我回答了另一个问题,我也会尝试这个问题。希望它给予更多的支持;)

好吧,首先我们定义类

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

【讨论】:

  • 我收到了sqlalchemy.exceptions.NoReferencedTableError: Could not find table 'items' with which to generate a foreign key
  • 已修复!必须从Note.id_item 中删除ForeignKey('items.id') 并在Item 的声明后添加Note.__table__.append_constraint(ForeignKeyConstraint(['id_item'], ['items.id']))。还必须在Item._notesdict 中将Note.name 替换为Note.__table__.c.name
  • @martin:奇怪!您使用的是哪个版本的 sqlalchemy?代码在我的机器上运行完全一样。
  • 我刚刚确认,这里不需要修复。它只是运行。
  • @nosklo:我使用的是 0.4.8。如果没有我之前评论中的循环依赖解决方法,它将无法运行...
猜你喜欢
  • 2010-10-21
  • 1970-01-01
  • 2011-03-23
  • 1970-01-01
  • 2012-10-19
  • 2016-08-01
  • 2014-05-06
  • 1970-01-01
  • 2014-05-28
相关资源
最近更新 更多