Skip to content

query_first_or_default

query_first_or_default can execute a query and serialize the first result, or return a default value if the result set contains no records.

Parameters🔗

name type description optional default
sql str the sql query str to execute 👎
default Any any object to return if the result set is empty 👎
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


sentinel = object()


with connect() as commands:
    task = commands.query_first_or_default("select * from task where id = -1", model=Task, default=sentinel)

if task is sentinel:
    print("No results found!")
# No results found!
(This script is complete, it should run "as is")