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

前端 未结 2 700
感情败类
感情败类 2020-12-05 06:18

As Mentioned here I created View.

Is following possible to create view class for using with session?

v = Table(\'viewname\', metadata, autoload=True)         


        
相关标签:
2条回答
  • 2020-12-05 06:45

    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.

    0 讨论(0)
  • 2020-12-05 06:51

    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.

    0 讨论(0)
提交回复
热议问题