Is possible to mapping view with class using mapper in SqlAlchemy?

orm, python, python-2.7, sqlalchemy

Solution

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)

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.

Problem

As Mentioned here I created View. 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) ```

Original source

Related problems