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.1.0.tar.gz (4.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic_sqlalchemy_filter-0.1.0-py3-none-any.whl (5.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pydantic_sqlalchemy_filter-0.1.0.tar.gz
  • Upload date:
  • Size: 4.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.11.11 Linux/6.8.0-1017-azure

File hashes

Hashes for pydantic_sqlalchemy_filter-0.1.0.tar.gz
Algorithm Hash digest
SHA256 aa9e2a3cb28fb123e1ae0154c964374f59b2f9e635bc258f4dd8dd5fae0c1828
MD5 dc9086b26249bb050891394f4e3a4aa1
BLAKE2b-256 d0a9464b38b1ec5e7c83a7de69948794b36ec7e1cd25474b2ffdbc09ad9bd16d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pydantic_sqlalchemy_filter-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 023b78746ea40fdd71a6fce5fb72045c7de021d883b9e1b62d81469313eca9e0
MD5 f2e2a896599c41e5342e076d719e659d
BLAKE2b-256 392f7f65dda99e063cec030ecaaa528e01136e48a5baeffa38f5475d451b07b1

See more details on using hashes here.

Supported by

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