Thanks, that does make more sense.
I ended up writing a little wrapper that allows me to create the query in
my service including the offset/limit and continue to add additional
filters, etc. when it's run.
class PagedQuery:
def __init__(self, query: orm.Query):
self.logger: logging.Logger = logging.getLogger(self.__module__)
self.query: orm.Query = query
self._limit: int = None
self._offset: int = None
def __getattr__(self, item: Text):
try:
return self.__getattribute__(item)
except AttributeError:
def call(*args, **kwargs):
self.query = getattr(self.query, item)(*args, **kwargs)
return self
return call
def limit(self, limit: int):
self._limit = limit
return self
def offset(self, offset: int):
self._offset = offset
return self
def all(self):
count = self.query.count()
self.logger.debug(f"Paging results, count={count},
offset={self._offset}, limit={self._limit}")
data = self.query \
.limit(self._limit) \
.offset(self._offset) \
.all()
return {
'total_count': count,
'data': data
}
On Monday, April 1, 2019 at 11:10:52 AM UTC-5, Derek Lambert wrote:
>
> Is it possible to return a query's results as a dictionary containing the
> total count and a limited portion of the results?
>
> query = session.query(Item)
>
> results = {
> 'total_count': query.count(),
> 'data': query.offset(0).limit(50).all(),
> }
>
>
> assert session.query(*magic_here*).*more_magic*().offset(0).limit(50).all()
> == results
>
> I feel like I accidentally hit on something like this a while back, but
> can't recall how or find any similar examples.
>
> Thanks,
> Derek
>
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
http://www.sqlalchemy.org/
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable
Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.