Syed Habib M
Syed Habib M

Reputation: 1817

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

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)

Upvotes: 15

Views: 18085

Answers (2)

Syed Habib M
Syed Habib M

Reputation: 1817

Finally I found it.

We can create class for sql view's. Here is simple example.

class ViewName(Base):
    __table__ = Table(
        'viewname', 
        Base.metadata,
        Column('id', Integer, primary_key=True),
        Column('foreign_key', Integer, ForeignKey('sometablename.id'),
        autoload=True, autoload_with=engine
    )

That's it. We can access "viewname" table using ViewName class.

Thank you for all who are respond me.

Upvotes: 25

stephan
stephan

Reputation: 10265

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.

Upvotes: 15

Related Questions