声明式SQLAlchemy中的标签字典? [英] Dictionary of tags in declarative SQLAlchemy?

查看:109
本文介绍了声明式SQLAlchemy中的标签字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个很大的代码库,该代码库已使用sqlalchemy.ext.declarative实现,并且我需要向其中一个类添加类似dict的属性.我需要的内容与此问题中的内容相同,但是是以声明性的方式.任何对SQLAlchemy有更多了解的人都可以举一个例子吗? 预先感谢...

I am working on a quite large code base that has been implemented using sqlalchemy.ext.declarative, and I need to add a dict-like property to one of the classes. What I need is the same as in this question, but in a declarative fashion. Can anyone with more knowledge in SQLAlchemy give me an example? Thanks in advance...

推荐答案

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

Declarative is just another way of defining things. Virtually you end up with the exact same environment than if you used separated mapping.

由于我回答了另一个问题,所以我也会尝试这个问题.希望它能带来更多的支持;)

Since I answered the other question, I'll try this one as well. Hope it gives more 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

我得到:

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

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

Now let's check the notes table...

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中的标签字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆