可以在SqlAlchemy中使用mapper使用类映射视图吗? [英] Is possible to mapping view with class using mapper in 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中使用mapper使用类映射视图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!