SQLAlchemy 中的 Model.query 和 session.query(Model) 有什么区别? [英] What's the difference between Model.query and session.query(Model) in SQLAlchemy?
问题描述
我是 SQLAlchemy 的初学者,发现查询可以通过 2 种方法完成:
I'm a beginner in SQLAlchemy and found query can be done in 2 method:
方法一:
DBSession = scoped_session(sessionmaker())
class _Base(object):
query = DBSession.query_property()
Base = declarative_base(cls=_Base)
class SomeModel(Base):
key = Column(Unicode, primary_key=True)
value = Column(Unicode)
# When querying
result = SomeModel.query.filter(...)
方法二
DBSession = scoped_session(sessionmaker())
Base = declarative_base()
class SomeModel(Base):
key = Column(Unicode, primary_key=True)
value = Column(Unicode)
# When querying
session = DBSession()
result = session.query(SomeModel).filter(...)
它们之间有什么区别吗?
Is there any difference between them?
推荐答案
在上面的代码中,没有什么区别.这是因为,在第一个示例的第 3 行:
In the code above, there is no difference. This is because, in line 3 of the first example:
query
属性明确绑定到DBSession
- 没有自定义的
Query
对象传递给query_property
- the
query
property is explicitly bound toDBSession
- there is no custom
Query
object passed toquery_property
正如@petr-viktorin 在此处的答案中指出的那样,在定义模型之前必须有可用的会话在第一个示例中,这可能会出现问题,具体取决于您的应用程序的结构.
As @petr-viktorin points out in the answer here, there must be a session available before you define your model in the first example, which might be problematic depending on the structure of your application.
但是,如果您需要一个自定义查询来自动向所有查询添加额外的查询参数,那么只有第一个示例允许这样做.从 sqlalchemy.orm.query.Query
继承的自定义查询类可以作为参数传递给 query_property
.这个问题展示了这种模式的一个例子.
If, however, you need a custom query that adds additional query parameters automatically to all queries, then only the first example will allow that. A custom query class that inherits from sqlalchemy.orm.query.Query
can be passed as an argument to query_property
. This question shows an example of that pattern.
即使模型对象上定义了自定义查询属性,在使用 session.query
进行查询时也不会使用该属性,如第二个示例的最后一行.这意味着如果您需要自定义查询类,则类似于第一个示例的唯一选项.
Even if a model object has a custom query property defined on it, that property is not used when querying with session.query
, as in the last line in the second example. This means something like the first example the only option if you need a custom query class.
这篇关于SQLAlchemy 中的 Model.query 和 session.query(Model) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!