Skip to main content

Implement simple API filter interface for Sqlalchemy

Project description

Stack:

Installation

pip install pydantic-sqlalchemy-filter

Usage

Implement UserFilter

from pydantic_sqlalchemy_filter import BaseQueryBuilder, DatabaseModel


class UserFilter(BaseQueryBuilder):
    username: str | None = Field(default=None)
    order_by: str | None = Field(default='username', alias='orderBy')

    def _filter(
        self,
        model: DatabaseModel,
        exclude_deleted: bool = False,
        query: sqlalchemy.Select | None = None,
    ) -> sqlalchemy.Select:
        if query is None:
            query = self.build_base_query(
                model=model,
                exclude_deleted=exclude_deleted,
            )

        if self.username is not None
            query = query.filter_by(username=self.username)

        return query

In FastAPI router:

    @router.get(path='')
    async def get_all_filtered_users(
        query_builder: Annotated[UserFilter, Depends()],
        session: Annotated[AsyncSession, Depends(get_async_session)],
    ) -> list[Users]:
        query = query_builder.build_select_query(model=User)
        results = await session.execute(query)
        users = results.scalars().all()

        return list(users)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydantic_sqlalchemy_filter-0.0.8.tar.gz (4.5 kB view details)

Uploaded Source

Built Distribution

File details

Details for the file pydantic_sqlalchemy_filter-0.0.8.tar.gz.

File metadata

  • Download URL: pydantic_sqlalchemy_filter-0.0.8.tar.gz
  • Upload date:
  • Size: 4.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.11.10 Linux/6.5.0-1025-azure

File hashes

Hashes for pydantic_sqlalchemy_filter-0.0.8.tar.gz
Algorithm Hash digest
SHA256 67d8bb2096c4095a49d5f5881296a371261647661e63b2ac509fa975c56cc023
MD5 21e76da0a03a78fbea858ba4a04e269f
BLAKE2b-256 a0896d6fcd48ca7c7b23bc90d15e4b419575f0f69430f8daf5a968dd89b54401

See more details on using hashes here.

File details

Details for the file pydantic_sqlalchemy_filter-0.0.8-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_sqlalchemy_filter-0.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 4faa9cac26de2af2976034b638b963eac0635c038158652537f553dd8bf57867
MD5 482ce969a8c074f9355b4e5d681547d6
BLAKE2b-256 df20a027fa1d5ffeccf5f615b3cf8fea9084f05c5b0497f0bea3a2f60c3da1ca

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page