Python 如何在 sqlalchemy 中查询表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3618690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to query a table, in sqlalchemy
提问by Freewind
I know how to query on a model now. Suppose there is a Questionmodel:
我现在知道如何查询模型了。假设有一个Question模型:
class Question(Base):
__tablename__ = "questions"
id=Column(...)
user_id=Column(...)
...
Now, I can do:
现在,我可以这样做:
question = Session.query(Question).filter_by(user_id=123).one()
But, now, I have a table (not a model) questions:
但是,现在,我有一张桌子(不是模型)questions:
questions = Table('questions', Base.metadata,
Column(id, ...),
Column(user_id, ...),
....)
How to query it as what I do with models?
如何像我对模型所做的那样查询它?
Session.query(questions).filter_by(user_id=123).one()
This will report an error:
这会报错:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "E:\Python27\lib\site-packages\sqlalchemy-0.6.3-py2.7.egg\sqlalchemy\orm\query.py", line 851, in filter_by
for key, value in kwargs.iteritems()]
File "E:\Python27\lib\site-packages\sqlalchemy-0.6.3-py2.7.egg\sqlalchemy\orm\util.py", line 567, in _entity_descriptor
desc = entity.class_manager[key]
AttributeError: 'NoneType' object has no attribute 'class_manager'
But:
但:
Session.query(questions).all()
is OK.
没问题。
Is filter_byonly work for models? How can I query on tables?
是filter_by只为模型的工作?如何查询表?
采纳答案by Jochen Ritzel
I think it's Session.query(questions).filter(questions.c.user_id==123).one()
我想这是 Session.query(questions).filter(questions.c.user_id==123).one()
回答by Noumenon
You can query tables that were created with the Table constructor using Session.query(Base.metadata.tables['myTable']).all().
您可以查询使用 Table 构造函数创建的表 Session.query(Base.metadata.tables['myTable']).all()。

