### Quick Start: conftest.py Setup Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/contrib/unittest.md Example of a conftest.py file to provide an isolated database context for each test using `tortoise_test_context`. ```APIDOC ## Quick Start: conftest.py Setup ### Description This snippet shows how to configure `conftest.py` to use `tortoise_test_context` for isolated database testing with pytest. ### Method Fixture setup using `pytest_asyncio` ### Endpoint N/A ### Parameters N/A ### Request Example ```python import os import pytest_asyncio from tortoise.contrib.test import tortoise_test_context @pytest_asyncio.fixture async def db(): """Provide isolated database context for each test.""" db_url = os.getenv("TORTOISE_TEST_DB", "sqlite://:memory:") async with tortoise_test_context(["myapp.models"], db_url=db_url) as ctx: yield ctx ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Quick Start: Async Test Example Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/contrib/unittest.md Example of an asynchronous test function that utilizes the `db` fixture for database interactions. ```APIDOC ## Quick Start: Async Test Example ### Description This snippet demonstrates how to write an asynchronous test function that leverages the `db` fixture provided by `conftest.py` for database operations. ### Method Asynchronous test function ### Endpoint N/A ### Parameters N/A ### Request Example ```python import pytest from myapp.models import User @pytest.mark.asyncio async def test_create_user(db): user = await User.create(name="Test User", email="test@example.com") assert user.id is not None assert user.name == "Test User" @pytest.mark.asyncio async def test_filter_users(db): await User.create(name="Alice") await User.create(name="Bob") users = await User.filter(name="Alice") assert len(users) == 1 assert users[0].name == "Alice" ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Create and Serialize Objects Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/contrib/pydantic.md Example of creating objects in an async context to be serialized. ```python # Create objects tournament = await Tournament.create(name="New Tournament") await Event.create(name="Event 1", tournament=tournament) await Event.create(name="Event 2", tournament=tournament) ``` -------------------------------- ### PostgreSQL DB_URL Examples Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/databases.md Configure PostgreSQL databases using `asyncpg` or `psycopg` drivers with specific URL schemes. ```postgres postgres://postgres:pass@db.host:5432/somedb ``` ```psycopg psycopg://postgres:pass@db.host:5432/somedb ``` ```asyncpg asyncpg://postgres:pass@db.host:5432/somedb ``` -------------------------------- ### Tortoise CLI Shell Installation Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/cli.md Instructions for installing the necessary dependencies (IPython or ptpython) to use the interactive Tortoise shell. IPython is recommended for better async/await support. ```shell # Install IPython (recommended) pip install tortoise-orm[ipython] # Or install ptpython pip install tortoise-orm[ptpython] ``` -------------------------------- ### SQLite DB_URL Example Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/databases.md Configure SQLite databases using a URL format like `sqlite:///path/to/db.sqlite3`. ```sqlite sqlite:///data/db.sqlite ``` -------------------------------- ### Initialize Tortoise-ORM Migrations Source: https://github.com/tortoise/tortoise-orm/blob/develop/examples/fastapi/README.rst Use this command to initialize the migrations directory for Tortoise-ORM. This is a one-time setup step. ```sh python -m tortoise -c config.TORTOISE_ORM init ``` -------------------------------- ### Define primary keys Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/models.md Examples of setting different field types as the primary key. ```python id = fields.IntField(primary_key=True) checksum = fields.CharField(primary_key=True) guid = fields.UUIDField(primary_key=True) ``` -------------------------------- ### Running Quart with Tortoise-ORM Source: https://github.com/tortoise/tortoise-orm/blob/develop/examples/quart/README.rst Demonstrates how to use the Quart CLI to manage Tortoise-ORM schemas and start the development server. Ensure the application path is explicit and not set to __main__. ```bash QUART_APP=main quart generate-schemas QUART_APP=main quart run ``` -------------------------------- ### Usage Example Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/validators.md Demonstrates how to use validators with a model field. ```APIDOC ## Usage You can pass a list of validators to Field parameter validators: ```python3 class ValidatorModel(Model): regex = fields.CharField(max_length=100, null=True, validators=[RegexValidator("abc.+", re.I)]) # oh no, this will raise ValidationError! await ValidatorModel.create(regex="ccc") # this is great! await ValidatorModel.create(regex="abcd") ``` ``` -------------------------------- ### MySQL DB_URL Example Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/databases.md Configure MySQL/MariaDB databases using a URL format like `mysql://user:password@host:port/dbname`. ```mysql mysql://myuser:mypass@db.host:3306/somedb ``` -------------------------------- ### Executing PyPika Queries Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/direct_queries.md Shows how to execute a constructed PyPika query using execute_pypika. It includes examples for default connections and specifying a custom database connection. ```python from pypika_tortoise import Query from tortoise.query_api import execute_pypika table = Tournament.get_table() query = Query.from_(table).select(table.id, table.name).where(table.name == "Champions") result = await execute_pypika(query) print(result.rows) print(result.rows_affected) # Using a specific connection from tortoise.connection import get_connection db = get_connection("analytics") result = await execute_pypika(query, using_db=db) ``` -------------------------------- ### Microsoft SQL Server DB_URL Example with Driver Options Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/databases.md Configure Microsoft SQL Server databases, specifying the ODBC driver and connection options like `encrypt` and `trust_server_certificate`. ```mssql mssql://myuser:mypass@db.host:1433/somedb?driver=ODBC%20Driver%2018%20for%20SQL%20Server&encrypt=no&trust_server_certificate=yes ``` -------------------------------- ### GET / Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/examples/blacksheep.md Retrieves a list of all users from the database. ```APIDOC ## GET / ### Description Fetch all user records from the database. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **users** (array) - List of User objects #### Response Example [ {"id": "550e8400-e29b-41d4-a716-446655440000", "username": "johndoe"} ] ``` -------------------------------- ### Execute Manual SQL Queries Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/examples/basic.md Provides examples of executing raw SQL queries using the connection object. Includes demonstrations of parameterized queries and transaction management using the in_transaction context manager. ```python from tortoise import Tortoise, connections, fields, run_async from tortoise.models import Model from tortoise.transactions import in_transaction class Event(Model): id = fields.IntField(primary_key=True) name = fields.TextField() timestamp = fields.DatetimeField(auto_now_add=True) async def run(): await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]}) await Tortoise.generate_schemas() conn = connections.get("default") await conn.execute_query("INSERT INTO event (name) VALUES ('Foo')") await conn.execute_query("INSERT INTO event (name) VALUES (?)", ["Bar"]) async with in_transaction("default") as tconn: await tconn.execute_query("INSERT INTO event (name) VALUES ('Moo')") async with in_transaction("default") as tconn: await tconn.execute_query("INSERT INTO event (name) VALUES ('Sheep')") await tconn.rollback() val = await conn.execute_query_dict("SELECT * FROM event") print(val) if __name__ == "__main__": run_async(run()) ``` -------------------------------- ### Define basic models Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/models.md Example of defining Tournament, Event, and Team models with various field types and relationships. ```python class Tournament(Model): id = fields.IntField(primary_key=True) name = fields.TextField() created = fields.DatetimeField(auto_now_add=True) def __str__(self): return self.name class Event(Model): id = fields.IntField(primary_key=True) name = fields.TextField() tournament = fields.ForeignKeyField('models.Tournament', related_name='events') participants = fields.ManyToManyField('models.Team', related_name='events', through='event_team') modified = fields.DatetimeField(auto_now=True) prize = fields.DecimalField(max_digits=10, decimal_places=2, null=True) def __str__(self): return self.name class Team(Model): id = fields.IntField(primary_key=True) name = fields.TextField() def __str__(self): return self.name ``` -------------------------------- ### Define relationship fields Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/models.md Examples of defining ForeignKey, ManyToMany, and other field types. ```python tournament = fields.ForeignKeyField('models.Tournament', related_name='events') participants = fields.ManyToManyField('models.Team', related_name='events') modified = fields.DatetimeField(auto_now=True) prize = fields.DecimalField(max_digits=10, decimal_places=2, null=True) ``` -------------------------------- ### Custom Validator Example (Function) Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/validators.md Demonstrates how to create a custom validator using a standalone function. ```python from tortoise.exceptions import ValidationError def validate_even_number(value:int): if value % 2 != 0: raise ValidationError(f"Value '{value}' is not an even number") ``` -------------------------------- ### Tortoise ORM CLI Migration Commands Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/migration.md This section provides examples of using the Tortoise ORM command-line interface (CLI) for managing database migrations. It includes commands for initializing migrations, creating new migration files, applying migrations, and reverting them. ```shell tortoise init ``` ```shell tortoise makemigrations ``` ```shell tortoise makemigrations --name add_posts_table ``` ```shell tortoise makemigrations --empty ``` ```shell tortoise migrate ``` ```shell tortoise migrate models ``` ```shell tortoise migrate models 0002_add_field ``` ```shell tortoise downgrade models ``` ```shell tortoise downgrade models 0001_initial ``` ```shell tortoise history ``` ```shell tortoise heads ``` ```shell tortoise sqlmigrate models 0001_initial ``` ```shell tortoise sqlmigrate models 0001_initial --backward ``` -------------------------------- ### Tortoise CLI Shell Usage Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/cli.md Demonstrates how to launch the interactive Tortoise shell. The shell requires either IPython or ptpython to be installed and provides an initialized Tortoise ORM environment. ```shell tortoise shell ``` -------------------------------- ### Async Test Case for User Creation Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/contrib/unittest.md An example of an asynchronous test function using the `db` fixture to create and verify a user. Requires the `pytest-asyncio` plugin. ```python import pytest from myapp.models import User @pytest.mark.asyncio async def test_create_user(db): user = await User.create(name="Test User", email="test@example.com") assert user.id is not None assert user.name == "Test User" ``` -------------------------------- ### Running Quart with Tortoise-ORM CLI Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/contrib/quart.md Commands to interact with a Quart application integrated with Tortoise-ORM. These commands allow for schema generation and starting the development server using the Quart CLI. ```bash # To generate schemas QUART_APP=main quart generate-schemas # To run QUART_APP=main quart run ``` -------------------------------- ### Early Partial Initialization of Models Source: https://github.com/tortoise/tortoise-orm/blob/develop/CHANGELOG.rst Enables early initialization of models, useful for schema generation without a full database setup. Models can be initialized from specified modules into a given namespace. ```python # Lets say you defined your models in "some/models.py", and "other/ddef.py" # And you are going to use them in the "model" namespace: Tortoise.init_models(["some.models", "other.ddef"], "models") ``` -------------------------------- ### Basic Pydantic Model Serialization Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/examples/pydantic.md This example demonstrates how to define Tortoise ORM models with various relationships and convert them into Pydantic models using pydantic_model_creator and pydantic_queryset_creator. It shows the initialization of an in-memory SQLite database, creation of records, and the serialization of single instances and querysets to JSON. ```python from tortoise import Tortoise, fields, run_async from tortoise.contrib.pydantic import pydantic_model_creator, pydantic_queryset_creator from tortoise.models import Model class Tournament(Model): id = fields.IntField(primary_key=True) name = fields.TextField() created_at = fields.DatetimeField(auto_now_add=True) events: fields.ReverseRelation["Event"] class Meta: ordering = ["name"] class Event(Model): id = fields.IntField(primary_key=True) name = fields.TextField() created_at = fields.DatetimeField(auto_now_add=True) tournament: fields.ForeignKeyNullableRelation[Tournament] = fields.ForeignKeyField( Tournament, related_name="events", null=True ) participants: fields.ManyToManyRelation["Team"] = fields.ManyToManyField( "models.Team", related_name="events", through="event_team" ) address: fields.OneToOneNullableRelation["Address"] class Meta: ordering = ["name"] class Address(Model): city = fields.CharField(max_length=64) street = fields.CharField(max_length=128) created_at = fields.DatetimeField(auto_now_add=True) event: fields.OneToOneRelation[Event] = fields.OneToOneField( Event, on_delete=fields.OnDelete.CASCADE, related_name="address", primary_key=True ) class Meta: ordering = ["city"] class Team(Model): id = fields.IntField(primary_key=True) name = fields.TextField() created_at = fields.DatetimeField(auto_now_add=True) events: fields.ManyToManyRelation[Event] class Meta: ordering = ["name"] async def run(): await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]}) await Tortoise.generate_schemas() Event_Pydantic = pydantic_model_creator(Event) Event_Pydantic_List = pydantic_queryset_creator(Event) Tournament_Pydantic = pydantic_model_creator(Tournament) Team_Pydantic = pydantic_model_creator(Team) tournament = await Tournament.create(name="New Tournament") event = await Event.create(name="Test", tournament=tournament) await Address.create(city="Santa Monica", street="Ocean", event=event) p = await Event_Pydantic.from_tortoise_orm(await Event.get(name="Test")) print("One Event:", p.model_dump_json(indent=4)) if __name__ == "__main__": run_async(run()) ``` -------------------------------- ### Initialize migration directories Source: https://github.com/tortoise/tortoise-orm/blob/develop/examples/schema_migrations_project/README.md Set up the migration structure using the project settings. ```bash uv run python -m tortoise -c examples.schema_migrations_project.settings.TORTOISE_ORM init ``` -------------------------------- ### Create PostgreSQL database Source: https://github.com/tortoise/tortoise-orm/blob/develop/examples/schema_migrations_project/README.md Initialize the database instance required for the project. ```bash createdb tortoise_schemas ``` -------------------------------- ### Define Article Model with Full-Text Search Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/contrib/postgres.md Example of defining a model with a TSVectorField for full-text search. It specifies source fields, configuration, weights, and whether to store the vector. This setup is required for efficient text searching. ```python from tortoise import fields, models from tortoise.contrib.postgres.fields import TSVectorField from tortoise.contrib.postgres.search import SearchQuery, SearchRank, SearchVector class Article(models.Model): title = fields.CharField(max_length=200) body = fields.TextField() search = TSVectorField( source_fields=("title", "body"), config="english", weights=("A", "B"), stored=True, ) ``` -------------------------------- ### Extending A Field Example Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/fields.md Example of subclassing `CharField` to create an `EnumField` that handles Enum types. ```APIDOC ## Extending A Field It is possible to subclass fields allowing use of arbitrary types as long as they can be represented in a database compatible format. An example of this would be a simple wrapper around the `CharField` to store and query Enum types. ```python from enum import Enum from typing import Type from tortoise import ConfigurationError from tortoise.fields import CharField class EnumField(CharField): """ An example extension to CharField that serializes Enums to and from a str representation in the DB. """ def __init__(self, enum_type: Type[Enum], **kwargs): super().__init__(128, **kwargs) if not issubclass(enum_type, Enum): raise ConfigurationError("{} is not a subclass of Enum!".format(enum_type)) self._enum_type = enum_type def to_db_value(self, value: Enum, instance) -> str: return value.value def to_python_value(self, value: str) -> Enum: try: return self._enum_type(value) except Exception: raise ValueError( "Database value {} does not exist on Enum {}.".format(value, self._enum_type) ) ``` When subclassing, make sure that the `to_db_value` returns the same type as the superclass (in the case of CharField, that is a `str`) and that, naturally, `to_python_value` accepts the same type in the value parameter (also `str`). ``` -------------------------------- ### Get Default Connection via Tortoise Class Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/connections.md Recommended way to get a specific database connection by its alias. Used for executing raw SQL queries. ```python from tortoise import Tortoise # Get a specific connection by alias conn = Tortoise.get_connection("default") # Execute raw queries result = await conn.execute_query('SELECT * FROM "user"') ``` -------------------------------- ### Get a single record by filter Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/models.md Use `get()` to retrieve a single model instance that matches the provided filter parameters. This method raises `DoesNotExist` if no record is found or `MultipleObjectsReturned` if more than one record matches. ```python3 user = await User.get(username="foo") ``` -------------------------------- ### Create Model Instance and Save to DB Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/models.md Use `create` to instantiate a model and immediately save it to the database. This is equivalent to creating an instance and then calling `.save()`. ```python user = await User.create(name="...", email="...") ``` ```python user = User(name="...", email="...") await user.save() ``` -------------------------------- ### get Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/query.md Fetches exactly one object matching the provided parameters. ```APIDOC ## get(*args, **kwargs) ### Description Fetch exactly one object matching the parameters. ### Parameters #### Args * `*args`: Positional arguments for filtering. * `**kwargs`: Keyword arguments for filtering. ``` -------------------------------- ### offset Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/query.md Sets the offset for the QuerySet, determining the starting point of results. ```APIDOC ## offset(offset) ### Description Query offset for QuerySet. ### Parameters #### offset * `offset`: The number of records to skip. ### Raises * `ParamsError`: Offset should be non-negative number. ``` -------------------------------- ### Create models with relationships Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/models.md Demonstrates creating models by passing objects or using DB-backing fields. ```python await SomeModel.create(tournament=the_tournament) # or somemodel.tournament=the_tournament ``` ```python await SomeModel.create(tournament_id=the_tournament.pk) ``` -------------------------------- ### Import Model base class Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/models.md Required import to start defining models. ```python from tortoise.models import Model ``` -------------------------------- ### Configure Multiple Databases Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/connections.md Sets up connections to multiple databases with distinct aliases and app configurations. Connections are accessed using their respective aliases. ```python await Tortoise.init( config={ "connections": { "default": "sqlite://primary.sqlite3", "secondary": "postgres://user:pass@localhost:5432/secondary", }, "apps": { "primary_models": { "models": ["myapp.primary_models"], "default_connection": "default", }, "secondary_models": { "models": ["myapp.secondary_models"], "default_connection": "secondary", } }, } ) # Access specific connections primary_conn = Tortoise.get_connection("default") secondary_conn = Tortoise.get_connection("secondary") ``` -------------------------------- ### Basic Filtering Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/query.md Example of a simple query to retrieve events with a rating greater than 5. ```APIDOC ## Basic Filtering ### Description This example demonstrates how to filter QuerySets based on a condition. ### Code Example ```python3 await Event.filter(rating__gt=5) ``` ``` -------------------------------- ### Tortoise CLI Basic Usage Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/cli.md Demonstrates basic commands for interacting with the Tortoise CLI, including help, configuration, and migration operations. ```shell tortoise -h tortoise -c settings.TORTOISE_ORM init tortoise makemigrations tortoise migrate ``` -------------------------------- ### GET /models/event Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/examples/basic.md Retrieves event records with support for filtering and prefetching related data. ```APIDOC ## GET /models/event ### Description Fetches event records from the database. Supports filtering by fields and prefetching related models like Tournaments or Teams. ### Method GET ### Endpoint /models/event ### Query Parameters - **username** (string) - Optional - Filter events by username. - **name** (string) - Optional - Filter events by name. ### Response #### Success Response (200) - **results** (array) - A list of event objects. #### Response Example [ {"id": 1, "name": "Updated name"} ] ``` -------------------------------- ### Preview SQL migration Source: https://github.com/tortoise/tortoise-orm/blob/develop/examples/schema_migrations_project/README.md Display the generated SQL for a specific migration file. ```bash uv run python -m tortoise -c examples.schema_migrations_project.settings.TORTOISE_ORM sqlmigrate shop 0001_initial ``` -------------------------------- ### Run FastAPI Application Source: https://github.com/tortoise/tortoise-orm/blob/develop/examples/fastapi/README.rst Start your FastAPI application with hot-reloading enabled using uvicorn. ```sh uvicorn main:app --reload ``` -------------------------------- ### explain Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/query.md Fetches and returns information about the query execution plan. ```APIDOC ## explain ### Description Fetch and return information about the query execution plan. This is done by executing an `EXPLAIN` query whose exact prefix depends on the database backend. ### Parameters * **output_fmt** (str) - Optional - The output format for the EXPLAIN result. (e.g., PostgreSQL: `text`, `json`, `xml`, `yaml`; MySQL: `json`, `traditional`, `tree`) * **options** (Dict) - Optional - Additional options for EXPLAIN (database-specific). ### Raises * **UnSupportedError** – If the database does not support the requested format or options. ``` -------------------------------- ### Tortoise CLI Init Command Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/cli.md Initializes migration packages for configured applications. This command ensures that each specified app has a 'migrations' module and that the package is importable. ```shell tortoise init tortoise init users billing ``` -------------------------------- ### Model Field Definition Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/fields.md Example of how to define fields within a Tortoise ORM Model class. ```APIDOC ## Model Field Definition ### Description Fields are defined as properties of a `Model` class object to map Python attributes to database columns. ### Request Example ```python from tortoise.models import Model from tortoise import fields class Tournament(Model): id = fields.IntField(primary_key=True) name = fields.CharField(max_length=255) ``` ``` -------------------------------- ### API Migration from Legacy Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/connections.md Guidance on migrating from the legacy `connections` singleton to the new API patterns in Tortoise ORM 1.0. ```APIDOC ## API Migration from Legacy If you’re upgrading from an older version that used the `connections` singleton, see the [Migration Guide: Tortoise 1.0](migration_guide.md#migration-guide) for details. **Quick reference:** | Old Pattern (Deprecated) | New Pattern | |------------------------------------|---------------------------------------------------| | `from tortoise import connections` | `from tortoise.connection import get_connections` | | `connections.get("alias")` | `Tortoise.get_connection("alias")` | | `connections.all()` | `get_connections().all()` | | `connections.close_all()` | `Tortoise.close_connections()` | ``` -------------------------------- ### URL Encode Password Example Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/databases.md Use `urllib.parse.quote_plus` to URL encode passwords containing special characters for use in DB_URL. ```python3 >>> import urllib.parse >>> urllib.parse.quote_plus("kx%jj5/g") 'kx%25jj5%2Fg' ``` -------------------------------- ### Generate initial migration Source: https://github.com/tortoise/tortoise-orm/blob/develop/examples/schema_migrations_project/README.md Create the initial migration files based on the defined models. ```bash uv run python -m tortoise -c examples.schema_migrations_project.settings.TORTOISE_ORM makemigrations ``` -------------------------------- ### Filter QuerySet by Field Prefix Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/query.md Filter records where a field starts with a specified string. Modifiers are separated by double underscores. ```python await Event.filter(name__startswith='FIFA') ``` -------------------------------- ### Configure model metadata with Meta Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/models.md Use the Meta class to define table names and unique constraints. ```python class Foo(Model): ... class Meta: table="custom_table" unique_together=(("field_a", "field_b"), ) ``` -------------------------------- ### Implement Migrations with RunPython and RunSQL Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/migration.md Demonstrates how to combine Python-based logic for complex calculations with direct SQL statements for efficient database updates within a Tortoise ORM migration class. ```python from tortoise.migrations import RunPython, RunSQL from decimal import Decimal async def calculate_totals(apps, schema_editor): Order = apps.get_model("shop", "Order") async for order in Order.all(): order.total = Decimal(order.subtotal) * Decimal("1.08") await order.save() class Migration(Migration): dependencies = [("shop", "0005_add_total_field")] operations = [ RunPython(code=calculate_totals, reverse_code=None), RunSQL( sql="UPDATE customer SET full_name = first_name || ' ' || last_name", reverse_sql="UPDATE customer SET full_name = NULL", ), ] ``` -------------------------------- ### Example JSON Schema Output Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/contrib/pydantic.md The resulting JSON schema for the Tournament_Pydantic model, showing excluded fields and added computed properties. ```json { "title": "Tournament", "description": "This references a Tournament", "type": "object", "properties": { "id": { "title": "Id", "type": "integer" }, "name": { "title": "Name", "type": "string" }, "events": { "title": "Events", "description": "The Tournament this happens in", "type": "array", "items": { "$ref": "#/definitions/Event" } }, "name_length": { "title": "Name Length", "description": "Computes length of name", "type": "integer" }, "events_num": { "title": "Events Num", "description": "Computes team size.", "type": "integer" } }, "definitions": { "Event": { "title": "Event", "description": "This references an Event in a Tournament", "type": "object", "properties": { "id": { "title": "Id", "type": "integer" }, "name": { "title": "Name", "type": "string" } } } } } ``` -------------------------------- ### Testing with Multiple Databases Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/contrib/unittest.md Example of setting up a pytest fixture to manage tests involving multiple database connections using `TortoiseContext`. ```APIDOC ## Testing with Multiple Databases ### Description This snippet demonstrates how to configure a pytest fixture for testing scenarios that require multiple database connections. ### Method Fixture setup using `pytest_asyncio` and `TortoiseContext` ### Endpoint N/A ### Parameters N/A ### Request Example ```python import pytest_asyncio from tortoise.context import TortoiseContext @pytest_asyncio.fixture async def multi_db(): """Fixture for testing with multiple databases.""" async with TortoiseContext() as ctx: await ctx.init( config={ "connections": { "primary": "sqlite://:memory:", "secondary": "sqlite://:memory:", }, "apps": { "models": { "models": ["myapp.models"], "default_connection": "primary", }, "archive": { "models": ["myapp.archive_models"], "default_connection": "secondary", } } } ) await ctx.generate_schemas() yield ctx ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### POST / Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/examples/blacksheep.md Creates a new user record in the database. ```APIDOC ## POST / ### Description Create a new user entry. ### Method POST ### Endpoint / ### Request Body - **username** (string) - Required - The username for the new user ### Request Example { "username": "newuser" } ### Response #### Success Response (201) - **id** (string) - The generated UUID of the user - **username** (string) - The username of the user ``` -------------------------------- ### Initialize Tortoise ORM with Model Discovery Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/CHANGELOG.rst Refactored `Tortoise.init()` to initialize all connections and discover models from a configuration object. This is a breaking change; you must now provide an app-to-modules map. ```python3 await Tortoise.init( db_url='sqlite://db.sqlite3', modules={'models': ['app.models']} ) # Generate the schema await Tortoise.generate_schemas() ``` -------------------------------- ### Tortoise ORM Initialization and Model Operations (Unchanged) Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/migration_guide.md Demonstrates initialization, schema generation, and basic model operations that remain unchanged in Tortoise ORM 1.0. These snippets are compatible with previous versions and continue to work as expected. ```python from tortoise import Tortoise # Initialization (unchanged) await Tortoise.init(config=...) await Tortoise.init(db_url="...", modules={...}) await Tortoise.generate_schemas() # Accessing apps (unchanged) Tortoise.apps Tortoise._inited # Model operations (unchanged) await User.create(name="test") await User.filter(name="test").first() # Framework integrations (unchanged for users) # FastAPI, Starlette, Sanic, etc. ``` -------------------------------- ### Get QuerySet for Earliest Record Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/models.md Use `earliest` to generate a QuerySet filtered to return the first record based on specified orderings. ```python Model.earliest(*orderings) ``` -------------------------------- ### OneToOneField Usage Example Source: https://github.com/tortoise/tortoise-orm/blob/develop/CHANGELOG.rst Demonstrates the usage of OneToOneField for defining a one-to-one relationship between models. This field can be set from the primary side and resolved from both sides. ```python event: fields.OneToOneRelation[Event] = fields.OneToOneField("models.Event", on_delete=fields.CASCADE, related_name="address") ``` -------------------------------- ### Apply migrations Source: https://github.com/tortoise/tortoise-orm/blob/develop/examples/schema_migrations_project/README.md Execute pending migrations against the database. ```bash uv run python -m tortoise -c examples.schema_migrations_project.settings.TORTOISE_ORM migrate ``` -------------------------------- ### Custom Even Number Validator Function Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/validators.md Example of creating a custom validator as a standalone function that raises `ValidationError` if the input number is not even. ```python from tortoise.exceptions import ValidationError # or use function instead of class def validate_even_number(value:int): if value % 2 != 0: raise ValidationError(f"Value '{value}' is not an even number") ``` -------------------------------- ### Using RegexValidator with a CharField Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/validators.md Demonstrates how to apply a RegexValidator to a CharField to enforce a specific pattern. This example shows both a successful and a failing validation case. ```python class ValidatorModel(Model): regex = fields.CharField(max_length=100, null=True, validators=[RegexValidator("abc.+", re.I)]) # oh no, this will raise ValidationError! await ValidatorModel.create(regex="ccc") # this is great! await ValidatorModel.create(regex="abcd") ``` -------------------------------- ### Handle Relations and Early Model Init with Pydantic Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/examples/pydantic.md Illustrates handling relationships and performing early model initialization when integrating Tortoise ORM with Pydantic. It shows creating Pydantic models for related Tortoise models and how early initialization affects schema generation. Dependencies include Tortoise ORM and Pydantic. ```python from tortoise import Tortoise, fields, run_async from tortoise.contrib.pydantic import pydantic_model_creator from tortoise.models import Model class Tournament(Model): """ This references a Tournament """ id = fields.IntField(primary_key=True) name = fields.CharField(max_length=100) #: The date-time the Tournament record was created at created_at = fields.DatetimeField(auto_now_add=True) class Event(Model): """ This references an Event in a Tournament """ id = fields.IntField(primary_key=True) name = fields.CharField(max_length=100) created_at = fields.DatetimeField(auto_now_add=True) tournament: fields.ForeignKeyRelation[Tournament] = fields.ForeignKeyField( Tournament, related_name="events", description="The Tournament this happens in" ) # Early model, does not include relations Tournament_Pydantic_Early = pydantic_model_creator(Tournament) # Print JSON-schema print(Tournament_Pydantic_Early.schema_json(indent=4)) # Initialise model structure early. This does not init any database structures Tortoise.init_models(["__main__"], "models") # We now have a complete model Tournament_Pydantic = pydantic_model_creator(Tournament) # Print JSON-schema print(Tournament_Pydantic.schema_json(indent=4)) # Note how both schema's don't follow relations back. Event_Pydantic = pydantic_model_creator(Event) ``` -------------------------------- ### Filter Related Events by Name Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/query.md Query related objects with predefined filters. This example retrieves events for a team that are specifically named 'First'. ```python await team.events.filter(name='First') ``` -------------------------------- ### Configure Connections via Dictionary Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/connections.md Initializes Tortoise ORM with a detailed configuration dictionary, specifying engines and credentials for connections. ```python await Tortoise.init( config={ "connections": { "default": { "engine": "tortoise.backends.sqlite", "credentials": {"file_path": "example.sqlite3"}, } }, "apps": { "models": {"models": ["__main__"], "default_connection": "default"} }, } ) ``` -------------------------------- ### Iterate and Print Participant Names Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/query.md Demonstrates iterating over related objects using 'async for'. This example prints the name of each participant associated with an event. ```python async for team in event.participants: print(team.name) ``` -------------------------------- ### Custom Even Number Validator Class Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/validators.md Example of creating a custom validator by inheriting from `tortoise.validators.Validator` and implementing the `__call__` method to check if a number is even. ```python from tortoise.validators import Validator from tortoise.exceptions import ValidationError class EvenNumberValidator(Validator): """ A validator to validate whether the given value is an even number or not. """ def __call__(self, value: int): if value % 2 != 0: raise ValidationError(f"Value '{value}' is not an even number") ``` -------------------------------- ### Configure Basic Logging for Tortoise-ORM Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/logging.md This snippet demonstrates how to set up a standard logging stream handler to capture and display debug information, including SQL queries, from both the database client and the main library logger. ```python import logging import sys fmt = logging.Formatter( fmt="%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) sh = logging.StreamHandler(sys.stdout) sh.setLevel(logging.DEBUG) sh.setFormatter(fmt) # will print debug sql logger_db_client = logging.getLogger("tortoise.db_client") logger_db_client.setLevel(logging.DEBUG) logger_db_client.addHandler(sh) logger_tortoise = logging.getLogger("tortoise") logger_tortoise.setLevel(logging.DEBUG) logger_tortoise.addHandler(sh) ``` -------------------------------- ### Improving Relational Type Hinting Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/models.md Provides an example of how to add type annotations to model fields to enable better autocompletion in editors for relational fields. ```APIDOC ## Improving Relational Type Hinting Add type annotations to your model fields to get better autocompletion for relations. ```python from tortoise.models import Model from tortoise import fields class Tournament(Model): id = fields.IntField(primary_key=True) name = fields.CharField(max_length=255) events: fields.ReverseRelation["Event"] def __str__(self): return self.name class Event(Model): id = fields.IntField(primary_key=True) name = fields.CharField(max_length=255) tournament: fields.ForeignKeyRelation[Tournament] = fields.ForeignKeyField( "models.Tournament", related_name="events" ) participants: fields.ManyToManyRelation["Team"] = fields.ManyToManyField( "models.Team", related_name="events", through="event_team" ) def __str__(self): return self.name class Team(Model): id = fields.IntField(primary_key=True) name = fields.CharField(max_length=255) events: fields.ManyToManyRelation[Event] def __str__(self): return self.name ``` ``` -------------------------------- ### Pytest Example for SQLite Only Tests Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/contrib/unittest.md Demonstrates using `requireCapability` within a pytest fixture to ensure a test function only executes when the database dialect is SQLite. ```python @requireCapability(dialect="sqlite") @pytest.mark.asyncio async def test_sqlite_only(db): # This test only runs on SQLite … ``` -------------------------------- ### Initialize Tortoise-ORM with custom SSL context Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/databases.md Use the verbose configuration structure to pass complex objects like SSL contexts that cannot be parsed from a standard connection URL. ```python # Here we create a custom SSL context import ssl ctx = ssl.create_default_context() # And in this example we disable validation... # Please don't do this. Look at the official Python ``ssl`` module documentation ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # Here we do a verbose init await Tortoise.init( config={ "connections": { "default": { "engine": "tortoise.backends.asyncpg", "credentials": { "database": None, "host": "127.0.0.1", "password": "moo", "port": 54321, "user": "postgres", "ssl": ctx # Here we pass in the SSL context } } }, "apps": { "models": { "models": ["some.models"], "default_connection": "default", } }, } ) ``` -------------------------------- ### Get Connection via Helper Functions Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/connections.md Provides direct access to the connection handler. Use `get_connection` for a specific connection or `get_connections` to access all connections. ```python from tortoise.connection import get_connection, get_connections # Get a specific connection conn = get_connection("default") # Get the connection handler (access to all connections) handler = get_connections() all_connections = handler.all() ``` -------------------------------- ### AIOHTTP Web Application with Tortoise ORM (Python) Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/examples/aiohttp.md Sets up an aiohttp web server and integrates Tortoise ORM for database interactions. It defines routes for listing all users and adding a new user, utilizing the previously defined 'Users' model. The Tortoise ORM is registered with the aiohttp application. ```python # pylint: disable=E0401,E0611 import logging from aiohttp import web from models import Users from tortoise.contrib.aiohttp import register_tortoise logging.basicConfig(level=logging.DEBUG) async def list_all(request): users = await Users.all() return web.json_response({"users": [str(user) for user in users]}) async def add_user(request): user = await Users.create(name="New User") return web.json_response({"user": str(user)}) app = web.Application() app.add_routes([web.get("/", list_all), web.post("/user", add_user)]) register_tortoise( app, db_url="sqlite://:memory:", modules={"models": ["models"]}, generate_schemas=True ) if __name__ == "__main__": web.run_app(app, port=5000) ``` -------------------------------- ### Configure Connections via DB URL Source: https://github.com/tortoise/tortoise-orm/blob/develop/docs/connections.md Initializes Tortoise ORM using a simple database URL string for the connection. ```python await Tortoise.init( db_url="sqlite://example.sqlite3", modules={"models": ["__main__"]} ) ```