[英]getting sqlalchemy view reflection to work in flask-sqlalchemy
Flask-SQLAlchemy's support of SQLAlchemy's reflection doesn't seem to be working quite right for me. Flask-SQLAlchemy对SQLAlchemy反射的支持似乎并不适合我。 I have a view
my_view
that I want to reflect on via autoload
. 我有一个
my_view
视图,我想通过autoload
来反思。
But I want my_view
to be a rich object and have various functions so I want my_view
to subclass db.Model
. 但我希望
my_view
是一个富对象并具有各种函数,所以我希望my_view
db.Model
。 I want it to pretty much work 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 during app bootstrap time I get an error: 但是在app bootstrap时间我收到一个错误:
<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.Table
instead of db.Model
it works: 但是,如果我使用
db.Table
而不是db.Model
它可以工作:
MyView = db.Table(
'my_view',
db.metadata,
...my column defs...
autoload=True,
autoload_with=db.engine
)
I really want to have an object and use db.Model
though, so I can implement __eq__()
and __json__()
and be able to do things like: 我真的想拥有一个对象并使用
db.Model
,所以我可以实现__eq__()
和__json__()
并且能够执行以下操作:
my_view_rows = session.query(MyView)\
.order_by(MyView.column_a)\
.all()
Anyone know why the db.Model
version of my code is not working? 任何人都知道为什么我的代码的
db.Model
版本不起作用? What do I need to do to get it working? 我需要做些什么才能让它发挥作用?
Using __table__ instead of __tablename__ and __table_args__ works. 使用__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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.