6. Select and page pending tasks
The task list needs incomplete tasks in a predictable order, with only one
page returned at a time. Describe that selection once with SQLQuery, then
use it for a page or a stream.
This example reuses the entity, DataS service, and database setup from the
previous steps. It creates two pending tasks and one completed task.
Save it as docs_src/tutorial/queries.py.
"""Select pending tasks, read a page, and stream the same selection."""
import asyncio
from docs_src.data.common import Task, database
from docs_src.data.quickstart import tasks
from fastsprout.data import DataR
from fastsprout.data.backend.sql import SQLQuery
async def main() -> None:
async with database():
await tasks.create(Task(id=1, title="Write documentation"))
await tasks.create(Task(id=2, title="Review documentation"))
await tasks.create(Task(id=3, title="Ship release", completed=True))
pending = (
SQLQuery(Task)
.where(Task.completed.eq(False))
.order_by(Task.id)
.limit(1)
)
page = await tasks.list(pending)
print("Matching tasks:", page.total)
print("Page:", [task.title for task in page.items])
async with DataR() as datar:
async for task in datar.stream(pending):
print("Streamed:", task.title)
if __name__ == "__main__":
asyncio.run(main())
Run it from your tutorial directory:
Result
Read the selection
where(Task.completed.eq(False)) selects pending tasks. order_by(Task.id)
puts them in ID order. limit(1) limits the returned page to one item.
tasks.list(pending) returns a page. Its total describes all matching tasks
before pagination, so it is two even though items contains one task.
datar.stream(pending) uses the same selection and yields its results through
async iteration. Consume the stream inside its DataR context so the SQL
session stays available until iteration finishes. Use a page for a bounded
response; use a stream when a caller should process results incrementally.
Try changing the limit to two, then select completed tasks instead. The Data guide covers additional conditions, joins, and transformations.
Previous: Transactions · Next: Connect actions in a workflow