本文整理汇总了Python中sqlalchemy.orm.Query方法的典型用法代码示例。如果您正苦于以下问题:Python orm.Query方法的具体用法?Python orm.Query怎么用?Python orm.Query使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.orm
的用法示例。
在下文中一共展示了orm.Query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute_query
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def execute_query(instance: PluginInstance, sql_query: Union[str, Query],
rows_as_dict: bool = False) -> web.Response:
try:
res: ResultProxy = instance.inst_db.execute(sql_query)
except exc.IntegrityError as e:
return resp.sql_integrity_error(e, sql_query)
except exc.OperationalError as e:
return resp.sql_operational_error(e, sql_query)
data = {
"ok": True,
"query": str(sql_query),
}
if res.returns_rows:
row: RowProxy
data["rows"] = [({key: check_type(value) for key, value in row.items()}
if rows_as_dict
else [check_type(value) for value in row])
for row in res]
data["columns"] = res.keys()
else:
data["rowcount"] = res.rowcount
if res.is_insert:
data["inserted_primary_key"] = res.inserted_primary_key
return web.json_response(data)
示例2: __init__
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def __init__(self, app=None, use_native_unicode=True, session_options=None, metadata=None):
if session_options is None:
session_options = {}
session_options.setdefault('scopefunc', connection_stack.__ident_func__)
self.use_native_unicode = use_native_unicode
self.session = self.create_scoped_session(session_options)
self.Model = self.make_declarative_base(metadata)
self.Query = BaseQuery
self._engine_lock = Lock()
self.app = app
_include_sqlalchemy(self)
if app is not None:
self.init_app(app)
示例3: query_constructor_filter_specifiable
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def query_constructor_filter_specifiable(
self,
transfer: CreditTransfer,
base_query: Query,
custom_filter: AggregationFilter) -> Query:
"""
Constructs a filtered query for aggregation, where the last filter step can be provided by the user
:param transfer:
:param base_query:
:param custom_filter:
:return: An SQLAlchemy Query Object
"""
filter_list = combine_filter_lists(
[
matching_sender_user_filter(transfer),
not_rejected_filter(),
after_time_period_filter(self.time_period_days),
custom_filter(transfer)
]
)
return base_query.filter(*filter_list)
示例4: __init__
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def __init__(self,
name: str,
applied_to_transfer_types: AppliedToTypes,
application_filter: ApplicationFilter,
time_period_days: int,
aggregation_filter: AggregationFilter = matching_transfer_type_filter
):
"""
:param name:
:param applied_to_transfer_types:
:param application_filter:
:param time_period_days: How many days back to include in aggregation
:param aggregation_filter: An SQLAlchemy Query Filter
"""
super().__init__(name, applied_to_transfer_types, application_filter)
self.time_period_days = time_period_days
self.custom_aggregation_filter = aggregation_filter
示例5: assertSelectedColumns
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def assertSelectedColumns(self, qs, *expected):
""" Test that the query has certain columns in the SELECT clause
:param qs: Query | query string
:param expected: list of expected column names
:returns: query string
"""
# Query?
if isinstance(qs, Query):
qs = q2sql(qs)
try:
self.assertEqual(
self._qs_selected_columns(qs),
set(expected)
)
return qs
except:
print(qs)
raise
示例6: mongoquery
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def mongoquery(cls, query_or_session: Union[Query, Session] = None) -> MongoQuery:
""" Build a MongoQuery
Note that when `None` is given, the resulting Query is not bound to any session!
You'll have to bind it manually, after calling .end()
:param query_or_session: Query to start with, or a session object to initiate the query with
:type query_or_session: sqlalchemy.orm.Query | sqlalchemy.orm.Session | None
:rtype: mongosql.MongoQuery
"""
if query_or_session is None:
query = Query([cls])
elif isinstance(query_or_session, Session):
query = query_or_session.query(cls)
elif isinstance(query_or_session, Query):
query = query_or_session
else:
raise ValueError('Argument must be Query or Session')
return cls._get_mongoquery().from_query(query)
示例7: query_model
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def query_model(self, query_obj: Union[Mapping, None] = None, from_query: Union[Query, None] = None) -> MongoQuery:
""" Make a MongoQuery using the provided Query Object
Note that you have to provide the MongoQuery yourself.
This is because it has to be properly configured with handler_settings.
:param query_obj: The Query Object to use
:param from_query: An optional Query to initialize MongoQuery with
:raises exc.InvalidColumnError: Invalid column name specified in the Query Object by the user
:raises exc.InvalidRelationError: Invalid relationship name specified in the Query Object by the user
:raises exc.InvalidQueryError: There is an error in the Query Object that the user has made
:raises exc.DisabledError: A feature is disabled; likely, due to a configuration issue. See handler_settings.
"""
# Validate
if not isinstance(query_obj, (Mapping, NoneType)):
raise exc.InvalidQueryError('Query Object must be either an object, or null')
# Query
return self._query_model(query_obj or {}, from_query) # ensure dict
示例8: _method_get
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def _method_get(self, *filter, **filter_by) -> object:
""" (CRUD method) Fetch a single entity: as in READ, single entity
Normally, used when the user has supplied a primary key:
GET /users/1
:param query_obj: Query Object
:param filter: Additional filter() criteria
:param filter_by: Additional filter_by() criteria
:raises sqlalchemy.orm.exc.NoResultFound: Nothing found
:raises sqlalchemy.orm.exc.MultipleResultsFound: Multiple found
:raises exc.InvalidQueryError: Query Object errors made by the user
"""
self._current_crud_method = CRUD_METHOD.GET
instance = self._get_one(self._get_query_object(), *filter, **filter_by)
return instance
示例9: _method_list_result_handler
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def _method_list_result_handler(self, query: Query) -> Union[int, Iterable[object], Iterable[Tuple]]:
""" Handle the results from method_list() """
# Handle: Query Object has count
if self._mongoquery.result_is_scalar():
return self._method_list_result__count(query.scalar())
# Handle: Query Object has group_by and yields tuples
if self._mongoquery.result_is_tuples():
# zip() column names together with the values,
# and make it into a dict
return self._method_list_result__groups(
dict(zip(row.keys(), row))
for row in query) # return a generator
# Regular result: entities
return self._method_list_result__entities(iter(query)) # Return an iterable that yields entities, not a list
示例10: _get_one
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def _get_one(self, query_obj: Mapping, *filter, **filter_by) -> object:
""" Utility method that fetches a single entity.
You will probably want to override it with custom error handling
:param query_obj: Query Object
:param filter: Additional filter() criteria
:param filter_by: Additional filter_by() criteria
:raises exc.InvalidQueryError: Query Object errors made by the user
:raises sqlalchemy.orm.exc.NoResultFound: Nothing found
:raises sqlalchemy.orm.exc.MultipleResultsFound: Multiple found
"""
# Query
query = self._mquery(query_obj, *filter, **filter_by)
# Result
return query.one()
示例11: __init__
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def __init__(self, query: Query):
# The original query. We store it just in case.
self._original_query = query
# The current query
# It differs from the originla query in that it is modified with a window function counting the rows
self._query = query
# The iterator for query results ; `None` if the query has not yet been executed
# If the query has been executed, there is always an iterator available, even if there were no results
self._query_iterator = None
# The total count ; `None` if the query has not yet been executed
self._count = None
# Whether the query is going to return single entities
self._single_entity = ( # copied from sqlalchemy.orm.loading.instances
not getattr(query, '_only_return_tuples', False) # accessing protected properties
and len(query._entities) == 1
and query._entities[0].supports_single_entity
)
# The method that will fix result rows
self._row_fixer = self._fix_result_tuple__single_entity if self._single_entity else self._fix_result_tuple__tuple
示例12: statement
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def statement(self):
"""The full SELECT statement represented by this Query.
The statement by default will not have disambiguating labels
applied to the construct unless with_labels(True) is called
first.
"""
stmt = self._compile_context(labels=self._with_labels).\
statement
if self._params:
stmt = stmt.params(self._params)
# TODO: there's no tests covering effects of
# the annotation not being there
return stmt._annotate({'no_replacement_traverse': True})
示例13: enable_eagerloads
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def enable_eagerloads(self, value):
"""Control whether or not eager joins and subqueries are
rendered.
When set to False, the returned Query will not render
eager joins regardless of :func:`~sqlalchemy.orm.joinedload`,
:func:`~sqlalchemy.orm.subqueryload` options
or mapper-level ``lazy='joined'``/``lazy='subquery'``
configurations.
This is used primarily when nesting the Query's
statement into a subquery or other
selectable, or when using :meth:`.Query.yield_per`.
"""
self._enable_eagerloads = value
示例14: with_labels
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def with_labels(self):
"""Apply column labels to the return value of Query.statement.
Indicates that this Query's `statement` accessor should return
a SELECT statement that applies labels to all columns in the
form <tablename>_<columnname>; this is commonly used to
disambiguate columns from multiple tables which have the same
name.
When the `Query` actually issues SQL to load rows, it always
uses column labeling.
.. note:: The :meth:`.Query.with_labels` method *only* applies
the output of :attr:`.Query.statement`, and *not* to any of
the result-row invoking systems of :class:`.Query` itself, e.g.
:meth:`.Query.first`, :meth:`.Query.all`, etc. To execute
a query using :meth:`.Query.with_labels`, invoke the
:attr:`.Query.statement` using :meth:`.Session.execute`::
result = session.execute(query.with_labels().statement)
"""
self._with_labels = True
示例15: enable_assertions
# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import Query [as 别名]
def enable_assertions(self, value):
"""Control whether assertions are generated.
When set to False, the returned Query will
not assert its state before certain operations,
including that LIMIT/OFFSET has not been applied
when filter() is called, no criterion exists
when get() is called, and no "from_statement()"
exists when filter()/order_by()/group_by() etc.
is called. This more permissive mode is used by
custom Query subclasses to specify criterion or
other modifiers outside of the usual usage patterns.
Care should be taken to ensure that the usage
pattern is even possible. A statement applied
by from_statement() will override any criterion
set by filter() or order_by(), for example.
"""
self._enable_assertions = value