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

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

问题描述

正如这里提到的我创建的查看.

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

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 中使用映射器将视图与类映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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