Getting sqlalchemy view reflection to work in a bulb-sqlalchemy

Flask-SQLAlchemy support for SQLAlchemy reflection does not seem to work perfectly for me. I have a view my_viewthat I want to conceive using autoload.

But I want it to my_viewbe a rich object and have different functions, so I want a my_viewsubclass db.Model. I want it to work pretty much like any other db model that is not a view.

I do it like this:

class MyView(db.Model):
    __tablename__ = 'my_view',
    __table_args__ = (
        db.UniqueConstraint('id', 'start_date'),
        {
            'autoload': True,
            'autoload_with': db.engine
        }
    )

    ...my column defs...

    ...extra functionality...

But while loading the application, I get an error message:

<snip>
File "env/lib/python3.4/site-packages/sqlalchemy/dialects/postgresql/base.py", line 2325, in get_columns
info_cache=kw.get('info_cache'))
File "<string>", line 2, in get_table_oid
File "env/lib/python3.4/site-packages/sqlalchemy/engine/reflection.py", line 54, in cache
ret = fn(self, con, *args, **kw)
File "env/lib/python3.4/site-packages/sqlalchemy/dialects/postgresql/base.py", line 2223, in get_table_oid
    raise exc.NoSuchTableError(table_name)
sqlalchemy.exc.NoSuchTableError: ('my_view',)

However, if I use db.Tableinstead db.Model, it works:

MyView = db.Table(
    'my_view',
    db.metadata,
    ...my column defs...
    autoload=True,
    autoload_with=db.engine
)

db.Model, , __eq__() __json__() , :

my_view_rows = session.query(MyView)\
                      .order_by(MyView.column_a)\
                      .all() 

- , db.Model ? , ?

+4
1

__table__ __tablename__ __table_args__ .

class MyView(db.Model):
    __table__ = db.Table(
        'my_view', db.metadata,
        db.Column('other_table_id', db.Integer, db.ForeignKey('other_table.id'), primary_key=True),
        ...other column defs...
        autoload=True,
        autoload_with=db.engine
    )

    other_table = db.relationship('OtherTable')
+3

Source: https://habr.com/ru/post/1613071/


All Articles