Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 321
Syed Habib M Avatar asked Dec 11 '13 11:12

Syed Habib M


2 Answers

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.

like image 162
stephan Avatar answered Nov 17 '22 16:11

stephan


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.

like image 24
Syed Habib M Avatar answered Nov 17 '22 15:11

Syed Habib M