PyPika for Tortoise-ORM

0.6.5 · active · verified Tue Apr 14

pypika-tortoise is an extension of the PyPika SQL query builder library, specifically designed to integrate seamlessly with Tortoise-ORM. It enables users to construct complex SQL queries using a Pythonic API directly from Tortoise-ORM models, leveraging PyPika's powerful query generation capabilities while ensuring compatibility with Tortoise-ORM's database interactions. The current version is 0.6.5, with its development closely tied to updates in `pypika` and `tortoise-orm`.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a Tortoise-ORM model and then use `pypika-tortoise` to construct SQL queries. It shows how to initialize `Table` directly from a model and build a `SELECT` query with filtering, ordering, and limiting. An example with aggregation functions is also included, showcasing how `pypika-tortoise` can generate complex SQL without needing an active database connection.

from tortoise import fields, models
from pypika_tortoise import Query, Table, functions as fn

# Define a Tortoise-ORM Model
class Product(models.Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=255)
    price = fields.DecimalField(max_digits=10, decimal_places=2)
    in_stock = fields.BooleanField(default=True)

    class Meta:
        table = "products" # Ensure the table name is set

# Create a Table object from the Tortoise-ORM Model
products_table = Table(Product)

# Build a query using pypika-tortoise, referencing model fields
query = Query.from_(products_table).select(
    products_table.id,
    products_table.name,
    products_table.price
).where(
    products_table.in_stock == True
).orderby(
    products_table.name
).limit(10)

# Generate the SQL string (does not execute against a DB)
sql_query = query.get_sql()
print(f"Generated SELECT SQL:\n{sql_query}")

# Example with aggregation using pypika_tortoise functions
query_agg = Query.from_(products_table).select(
    fn.Count(products_table.id).as_('total_products'),
    fn.Sum(products_table.price).as_('total_price_in_stock')
).where(
    products_table.in_stock == True
)

sql_agg_query = query_agg.get_sql()
print(f"\nGenerated AGGREGATION SQL:\n{sql_agg_query}")

view raw JSON →