栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

SQLAlchemy-标签字典

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SQLAlchemy-标签字典

简单的答案是 肯定的

只需使用关联代理:

from sqlalchemy import Column, Integer, String, Table, create_enginefrom sqlalchemy import orm, metaData, Column, ForeignKeyfrom sqlalchemy.orm import relation, mapper, sessionmakerfrom sqlalchemy.orm.collections import column_mapped_collectionfrom sqlalchemy.ext.associationproxy import association_proxy

创建一个测试环境:

engine = create_engine('sqlite:///:memory:', echo=True)meta = metaData(bind=engine)

定义表:

tb_items = Table('items', meta,         Column('id', Integer, primary_key=True),         Column('name', String(20)),        Column('description', String(100)),    )tb_notes = Table('notes', meta,         Column('id_item', Integer, ForeignKey('items.id'), primary_key=True),        Column('name', String(20), primary_key=True),        Column('value', String(100)),    )meta.create_all()

类(注意

association_proxy
类中的):

class Note(object):    def __init__(self, name, value):        self.name = name        self.value = valueclass Item(object):    def __init__(self, name, description=''):        self.name = name        self.description = description    notes = association_proxy('_notesdict', 'value', creator=Note)

对应:

mapper(Note, tb_notes)mapper(Item, tb_items, properties={        '_notesdict': relation(Note,   collection_class=column_mapped_collection(tb_notes.c.name)),    })

然后测试一下:

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'}

但是,那些在注释表中吗?

>>> print list(tb_notes.select().execute())[(1, u'color', u'orange'), (1, u'data', u'none'), (1, u'size', u'big')]

有用!!:)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669793.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号