可以在SqlAlchemy中使用mapper使用类映射视图吗? [英] Is possible to mapping view with class using mapper in SqlAlchemy?

查看:518
本文介绍了可以在SqlAlchemy中使用mapper使用类映射视图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此处提到的创建查看.

下面是否可以创建用于会话的视图类?

Is following possible to create view class for using with session?

v = Table('viewname', metadata, autoload=True)

class ViewName(object):
    def __init__(self, name):
       self.name = name

mapper(ViewName, v)

推荐答案

您可以执行此操作,但是必须手动定义主键.假设id是要用作主键的v列(就像我的原始示例一样)代码),它可以正常工作:

You can do this, but you have to define a primary key manually. Assuming that id is a column of v which you want to use as the primary key (as is the case in my original example code), this works:

from sqlalchemy import orm

class ViewName(object):
    def __init__(self, name):
       self.name = name

orm.mapper(ViewName, v, primary_key=[v.c.id])

Session = orm.sessionmaker(bind=engine)
for r in Session().query(ViewName):
    print r.id, r.number

要对此进行测试,只需将此片段粘贴到我的工作示例的末尾,上面链接的答案中即可.有关更多详细信息,请参见文档(例如,可以使用属性来定义外键.

To test this, just paste this snippet at the end of my working example in the answer linked above. See the documentation for more details (e.g. you can use properties to define foreign keys).

编辑(在

EDIT (van in a comment to my answer linked above): Alternatively, you can change the view definiton in my original code (and your question) slightly and write:

v = Table('viewname', metadata, Column('id', Integer, primary_key=True), autoload=True)

,即,已经在表定义中添加了主键.然后,您就不需要orm.mapper中的primary_key参数,并且问题中的其余代码都可以直接使用.

i.e., add the primary key in the table definition already. Then you don't need the primary_key argument in the orm.mapper and the rest of the code in your question works out of the box.

这篇关于可以在SqlAlchemy中使用mapper使用类映射视图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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