query_single
query_single
can execute a query and serialize the first result. It throws an exception if there is not exactly one
record in the result set.
Parameters🔗
name | type | description | optional | default |
---|---|---|---|---|
sql | str |
the sql query str to execute | ||
param | ParamType |
params to substitute in the query | None |
|
model | Any |
the callable to serialize the model; callable must be able to accept column names as kwargs. | dict |
First, Single and Default🔗
Be careful to use the right method. first
and single
methods are very different.
method | no item | one item | many items |
---|---|---|---|
first |
NoResultException |
item | first item |
single |
NoResultException |
item | MoreThanOneResultException |
first_or_default |
default | item | first item |
single_or_default |
default | item | MoreThanOneResultException |
Example🔗
Execute a query and map the first result to a dataclass.
import datetime
from dataclasses import dataclass
from pydapper import connect
@dataclass
class Task:
id: int
description: str
due_date: datetime.date
owner_id: int
with connect() as commands:
task = commands.query_single("select * from task where id = 1", model=Task)
print(task)
# Task(id=1, description='Set up a test database', due_date=datetime.date(2021, 12, 31), owner_id=1)