### Setup and Development Workflow Source: https://github.com/ormar-orm/ormar/blob/master/docs/contributing.md Clone the repository, install dependencies with poetry, create a new branch, and make your changes. This sets up the local environment for development. ```bash # 1. clone your fork and cd into the repo directory git clone git@github.com:/ormar.git cd ormar # 2. Install ormar, dependencies and test dependencies poetry install -E dev # 3. Checkout a new branch and make your changes git checkout -b my-new-feature-branch # make your changes... ``` -------------------------------- ### Complete Example with Transactional Operations Source: https://github.com/ormar-orm/ormar/blob/master/docs/transactions.md Demonstrates creating an author and multiple books within a single transaction. If any book creation fails, the entire operation is rolled back. Includes setup for models and database connection. ```python import sqlalchemy import ormar from ormar import DatabaseConnection DATABASE_URL = "sqlite+aiosqlite:///db.sqlite" base_ormar_config = ormar.OrmarConfig( metadata=sqlalchemy.MetaData(), database=DatabaseConnection(DATABASE_URL), ) class Author(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=255) class Book(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) title: str = ormar.String(max_length=255) author: Author = ormar.ForeignKey(Author) async def create_author_and_books_transactional(author_name: str, book_titles: list[str]): """ Create an author and multiple books in a single transaction. If any book fails to create, the entire operation is rolled back. """ database = Author.ormar_config.database async with database: try: async with database.transaction(): # Create author author = await Author.objects.create(name=author_name) # Create all books for title in book_titles: await Book.objects.create(title=title, author=author) print(f"Successfully created {author_name} with {len(book_titles)} books") return author except Exception as e: # Transaction is automatically rolled back on exception print(f"Failed to create author and books: {e}") # Author and all books are rolled back raise # Usage example async def main(): database = Author.ormar_config.database async with database: # Create tables sync_engine = sqlalchemy.create_engine( DATABASE_URL.replace('+aiosqlite', '') ) base_ormar_config.metadata.create_all(sync_engine) # Example 1: Successful transaction await create_author_and_books_transactional( "Stephen King", ["The Shining", "It", "The Stand"] ) # Example 2: Failed transaction (will rollback) try: await create_author_and_books_transactional( "Test Author", ["Book 1", None, "Book 3"] # None will cause an error ) except Exception: print("Transaction rolled back as expected") # Verify: Only Stephen King and his books exist authors = await Author.objects.all() print(f"Total authors: {len(authors)}") # Should be 1 books = await Book.objects.all() print(f"Total books: {len(books)}") # Should be 3 if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Sample Data Creation for Ormar Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/filter-and-sort.md Populates the database with sample Author and Book data for testing complex queries. This setup is necessary for the subsequent examples. ```python tolkien = await Author(name="J.R.R. Tolkien").save() await Book(author=tolkien, title="The Hobbit", year=1933).save() await Book(author=tolkien, title="The Lord of the Rings", year=1955).save() await Book(author=tolkien, title="The Silmarillion", year=1977).save() sapkowski = await Author(name="Andrzej Sapkowski").save() await Book(author=sapkowski, title="The Witcher", year=1990).save() await Book(author=sapkowski, title="The Tower of Fools", year=2002).save() ``` -------------------------------- ### Complete Migration Example: Before and After Source: https://github.com/ormar-orm/ormar/blob/master/docs/migration.md This example demonstrates the full migration of a model definition and table creation from Ormar < 0.22.0 to Ormar >= 0.22.0, highlighting all the changes discussed. ```python # Before (ormar < 0.22) import databases import sqlalchemy import ormar database = databases.Database("sqlite:///db.sqlite") metadata = sqlalchemy.MetaData() engine = sqlalchemy.create_engine("sqlite:///db.sqlite") base_ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, engine=engine, ) class Author(ormar.Model): ormar_config = base_ormar_config.copy(tablename="authors") id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) # Create tables metadata.create_all(engine) # After (ormar >= 0.22) import sqlalchemy import ormar from ormar import DatabaseConnection DATABASE_URL = "sqlite+aiosqlite:///db.sqlite" database = DatabaseConnection(DATABASE_URL) metadata = sqlalchemy.MetaData() base_ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, ) class Author(ormar.Model): ormar_config = base_ormar_config.copy(tablename="authors") id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) # Create tables with sync engine sync_engine = sqlalchemy.create_engine( DATABASE_URL.replace('+aiosqlite', '') ) metadata.create_all(sync_engine) ``` -------------------------------- ### Create Sample Data for Raw Data Example Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/raw-data.md Create and save sample data for the Category and Post models to be used in subsequent examples. ```python # sample data news = await Category(name="News", sort_order=0).save() await Post(name="Ormar strikes again!", category=news).save() await Post(name="Why don't you use ormar yet?", category=news).save() await Post(name="Check this out, ormar now for free", category=news).save() ``` -------------------------------- ### Install Ormar with SQLite Support Source: https://github.com/ormar-orm/ormar/blob/master/docs/install.md Install Ormar with optional support for SQLite. This includes the aiosqlite driver. ```bash pip install ormar[sqlite] ``` -------------------------------- ### Create Sample Data for Relation Example Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/raw-data.md Create and save sample User and Role data, establishing a ManyToMany relationship between them. ```python # sample data creator = await User(name="Anonymous").save() admin = await Role(name="admin").save() editor = await Role(name="editor").save() await creator.roles.add(admin) await creator.roles.add(editor) ``` -------------------------------- ### Install Ormar with Database Backends Source: https://context7.com/ormar-orm/ormar/llms.txt Install Ormar using pip, specifying the desired database backend extra (e.g., [sqlite], [postgresql], [mysql]). ```bash pip install ormar[sqlite] ``` ```bash pip install ormar[postgresql] ``` ```bash pip install ormar[mysql] ``` ```bash pip install ormar[all] ``` ```bash pip install ormar[crypto] ``` -------------------------------- ### Install Ormar with Orjson Support Source: https://github.com/ormar-orm/ormar/blob/master/docs/install.md Install Ormar with optional support for orjson for faster JSON parsing. This includes the orjson library. ```bash pip install ormar[orjson] ``` -------------------------------- ### Setup relation with Model instance Source: https://github.com/ormar-orm/ormar/blob/master/docs/relations/foreign-key.md Initialize a relation by passing a related `Model` instance to the constructor. ```python class Course(ormar.Model): ormar_config = base_ormar_config.copy(tablename="courses") id: int = ormar.Integer(primary_key=True) title: str = ormar.String(max_length=100) department: Department = ormar.ForeignKey(Department) class Department(ormar.Model): ormar_config = base_ormar_config.copy(tablename="departments") id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) courses: List[Course] = ormar.ManyToMany(Course) async def create_department(): department = await Department.objects.create(name="Science") course = await Course.objects.create(title="Physics", department=department) course_2 = await Course.objects.create(title="Chemistry", department=department) return department, course, course_2 ``` -------------------------------- ### Install Ormar with Crypto Support Source: https://github.com/ormar-orm/ormar/blob/master/docs/install.md Install Ormar with optional support for encrypted columns. This includes the cryptography library. ```bash pip install ormar[crypto] ``` -------------------------------- ### Install Ormar with PostgreSQL Support Source: https://github.com/ormar-orm/ormar/blob/master/docs/install.md Install Ormar with optional support for PostgreSQL. This includes the necessary drivers like asyncpg and psycopg2. ```bash pip install ormar[postgresql] ``` -------------------------------- ### Install Ormar Base Package Source: https://github.com/ormar-orm/ormar/blob/master/docs/install.md Install the core Ormar package using pip. This command installs the ORM and its essential dependencies like SQLAlchemy async and pydantic. ```bash pip install ormar ``` -------------------------------- ### Install Ormar with MySQL Support Source: https://github.com/ormar-orm/ormar/blob/master/docs/install.md Install Ormar with optional support for MySQL. This includes the necessary drivers like aiomysql and pymysql. ```bash pip install ormar[mysql] ``` -------------------------------- ### Demonstrate Custom QuerySet Functionality Source: https://context7.com/ormar-orm/ormar/llms.txt This example illustrates using the custom `active` and `get_or_404` methods on a model that utilizes a `SoftDeleteQuerySet`. ```python async def demo_custom_qs(): async with base_ormar_config.database: await Task.objects.create(title="Active Task") deleted = await Task.objects.create(title="Deleted Task", is_deleted=True) active_tasks = await Task.objects.active() assert len(active_tasks) == 1 assert active_tasks[0].title == "Active Task" task = await Task.objects.get_or_404(title="Active Task") assert task is not None try: await Task.objects.get_or_404(title="Does Not Exist") except HTTPException as e: assert e.status_code == 404 ``` -------------------------------- ### Demonstrate Proxy Model Inheritance Source: https://context7.com/ormar-orm/ormar/llms.txt This example shows how to create and query instances using a proxy model, verifying that it shares the same underlying table and adds custom methods. ```python async def demo_inheritance(): async with base_ormar_config.database: post = await BlogPost.objects.create(title="Hello World", body="Content here") assert post.published is False human = await Human.objects.create(first_name="Alan", last_name="Turing") # Query via proxy class user = await FullNameUser.objects.get(id=human.pk) assert user.full_name() == "Alan Turing" # Same underlying table assert await Human.objects.count() == await FullNameUser.objects.count() ``` -------------------------------- ### Hash Backend Example and Comparison Source: https://github.com/ormar-orm/ormar/blob/master/docs/fields/encryption.md Demonstrates setting up a HASH encrypted field and how to compare values. Full value comparison works, but partial filtering does not. ```python import hashlib import base64 import pytest from ormar import NoMatch # Assuming base_ormar_config and database are defined elsewhere # base_ormar_config = ormar.OrmarConfig(metadata=metadata, database=database) class Hash(ormar.Model): ormar_config = base_ormar_config.copy(tablename="hashes") id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=128, encrypt_secret="udxc32", encrypt_backend=ormar.EncryptBackends.HASH) # await Hash(name='test1').save() # note the steps to recreate the stored value # you can use also cryptography package instead of hashlib secret = hashlib.sha256("udxc32".encode()).digest() secret = base64.urlsafe_b64encode(secret) hashed_test1 = hashlib.sha512(secret + 'test1'.encode()).hexdigest() # full value comparison works # hash1 = await Hash.objects.get(name='test1') # assert hash1.name == hashed_test1 # but partial comparison does not (hashed strings are compared) # with pytest.raises(NoMatch): # await Filter.objects.get(name__icontains='test') ``` -------------------------------- ### Implementing a Dummy Encryption Backend Source: https://github.com/ormar-orm/ormar/blob/master/docs/fields/encryption.md Subclass `ormar.fields.EncryptBackend` to create a custom encryption solution. This example shows a dummy backend that performs no actual encryption or decryption. ```python class DummyBackend(ormar.fields.EncryptBackend): def _initialize_backend(self, secret_key: bytes) -> None: pass def encrypt(self, value: Any) -> str: return value def decrypt(self, value: Any) -> str: return value ``` -------------------------------- ### Setup relation with Primary Key value Source: https://github.com/ormar-orm/ormar/blob/master/docs/relations/foreign-key.md Initialize a relation by passing just the primary key column value of the related model. ```python class Course(ormar.Model): ormar_config = base_ormar_config.copy(tablename="courses") id: int = ormar.Integer(primary_key=True) title: str = ormar.String(max_length=100) department: Department = ormar.ForeignKey(Department) class Department(ormar.Model): ormar_config = base_ormar_config.copy(tablename="departments") id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) courses: List[Course] = ormar.ManyToMany(Course) async def create_department(): department = await Department.objects.create(name="Science") course = await Course.objects.create(title="Physics", department=department) course_2 = await Course.objects.create(title="Chemistry", department=department) return department, course, course_2 async def setup_relation_with_pk(): department = await Department.objects.get(pk=1) course = await Course(title="Biology", department=department.pk).save() return course ``` -------------------------------- ### Default Value Examples Source: https://github.com/ormar-orm/ormar/blob/master/docs/fields/common-parameters.md Demonstrates how to set a default value for a field using a static value or a Callable. Note the distinction between passing a value and a Callable pointer. ```python name: str = ormar.String(max_length=200, default="Name") ``` ```python created_date: datetime.datetime = ormar.DateTime(default=datetime.datetime.now()) ``` ```python created_date: datetime.datetime = ormar.DateTime(default=datetime.datetime.now) ``` -------------------------------- ### Setup relation with Dictionary Source: https://github.com/ormar-orm/ormar/blob/master/docs/relations/foreign-key.md Initialize a relation by passing a dictionary of key-values of the related model. This dictionary can be built manually or obtained using the `model_dump()` method. ```python class Course(ormar.Model): ormar_config = base_ormar_config.copy(tablename="courses") id: int = ormar.Integer(primary_key=True) title: str = ormar.String(max_length=100) department: Department = ormar.ForeignKey(Department) class Department(ormar.Model): ormar_config = base_ormar_config.copy(tablename="departments") id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) courses: List[Course] = ormar.ManyToMany(Course) async def create_department(): department = await Department.objects.create(name="Science") course = await Course.objects.create(title="Physics", department=department) course_2 = await Course.objects.create(title="Chemistry", department=department) return department, course, course_2 async def setup_relation_with_dict(): department = await Department.objects.get(pk=1) course_data = {"title": "History", "department": department.model_dump()} course = await Course(**course_data).save() return course ``` -------------------------------- ### Define Models for Raw Data Example Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/raw-data.md Define the Category and Post ORM models. These models will be used to demonstrate fetching raw data. ```python class Category(ormar.Model): ormar_config = base_ormar_config.copy(tablename="categories") id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=40) sort_order: int = ormar.Integer(nullable=True) class Post(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=200) category: Optional[Category] = ormar.ForeignKey(Category) ``` -------------------------------- ### Pytest Fixture for Database Setup Source: https://github.com/ormar-orm/ormar/blob/master/docs/fastapi/index.md A pytest fixture to create database tables before tests and drop them after the test module finishes. ```python @pytest.fixture(autouse=True, scope="module") def create_test_database(): engine = sqlalchemy.create_engine(DATABASE_URL) metadata.create_all(engine) yield metadata.drop_all(engine) ``` -------------------------------- ### get Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/filter-and-sort.md Retrieves the first row from the database that matches the specified criteria. It's a shortcut for `filter(*args, **kwargs).get()`. ```APIDOC ## get `get(*args, **kwargs) -> Model` Gets the first row from the db meeting the criteria set by kwargs. When any args and/or kwargs are passed it's a shortcut equivalent to calling `filter(*args, **kwargs).get()` !!!tip To read more about `filter` go to [filter](./#filter). To read more about `get` go to [read/get](../read/#get) ``` -------------------------------- ### Pagination in Ormar Source: https://github.com/ormar-orm/ormar/blob/master/README.md Explains how to implement pagination using limit(), offset(), and paginate() methods to control the number of returned rows and the starting point. ```python books = await Book.objects.limit(1).all() ``` ```python books = await Book.objects.limit(1).offset(1).all() ``` ```python books = await Book.objects.paginate(page=2, page_size=2).all() ``` -------------------------------- ### Fernet Backend Example and Limitations Source: https://github.com/ormar-orm/ormar/blob/master/docs/fields/encryption.md Demonstrates saving and retrieving data with FERNET encryption. Filtering and ordering are not possible due to the timestamp included in the encrypted value. ```python import pytest from ormar import NoMatch # Assuming base_ormar_config and database are defined elsewhere # base_ormar_config = ormar.OrmarConfig(metadata=metadata, database=database) class Filter(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100, encrypt_secret="asd123", encrypt_backend=ormar.EncryptBackends.FERNET) # await Filter(name='test1').save() # await Filter(name='test1').save() # values are properly encrypted and later decrypted # filters = await Filter.objects.all() # assert filters[0].name == filters[1].name == 'test1' # but you cannot filter at all since part of the fernet hash is a timestamp # which means that even if you encrypt the same string 2 times it will be different # with pytest.raises(NoMatch): # await Filter.objects.get(name='test1') ``` -------------------------------- ### Server Default Value Example Source: https://github.com/ormar-orm/ormar/blob/master/docs/fields/common-parameters.md Illustrates how to set a server-side default value using a SQL function or a text clause. This is passed directly to SQLAlchemy. ```python from sqlalchemy import text from ormar import DateTime class SampleModel: created_date: DateTime = DateTime(server_default=text("CURRENT_TIMESTAMP")) ``` -------------------------------- ### Ormar Custom Encryption Backend Source: https://context7.com/ormar-orm/ormar/llms.txt Illustrates how to implement and use a custom encryption backend by subclassing `ormar.fields.EncryptBackend`. The example uses Base64 encoding for demonstration purposes. ```python # Custom encryption backend class Base64Backend(ormar.fields.EncryptBackend): def _initialize_backend(self, secret_key: bytes) -> None: pass # no key needed for demo def encrypt(self, value) -> str: import base64 return base64.b64encode(str(value).encode()).decode() def decrypt(self, value) -> str: import base64 return base64.b64decode(value.encode()).decode() class SecretNote(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) content: str = ormar.String( max_length=500, encrypt_secret="ignored-by-custom", encrypt_backend=ormar.EncryptBackends.CUSTOM, encrypt_custom_backend=Base64Backend, ) ``` -------------------------------- ### Ormar Model with on_update Examples Source: https://github.com/ormar-orm/ormar/blob/master/docs/fields/common-parameters.md Demonstrates the usage of the `on_update` parameter for both callable and static values. It shows how `on_update` is applied during model updates and how explicit values override it. ```python from datetime import datetime class Task(ormar.Model): ormar_config = base_ormar_config.copy(tablename="tasks") id: int = ormar.Integer(primary_key=True) # callable - invoked on every update updated_at: datetime = ormar.DateTime( default=datetime.now, on_update=datetime.now ) # static value is_dirty: bool = ormar.Boolean(default=False, on_update=True) # static value - field keeps the value the caller passed if any revision: int = ormar.Integer(default=0, on_update=1) task = await Task.objects.create() assert task.is_dirty is False await task.update() assert task.is_dirty is True # on_update applied assert task.revision == 1 # on_update applied assert task.updated_at > created_time # on_update callable re-evaluated # explicit values override on_update await task.update(revision=5) assert task.revision == 5 # user value wins, on_update skipped ``` -------------------------------- ### Read Records with Ormar Source: https://github.com/ormar-orm/ormar/blob/master/docs/index.md Shows how to fetch single instances using get() and first(), access fields, handle relationships, and retrieve all records with all(). ```python # Fetch an instance, without loading a foreign key relationship on it. # Django style book = await Book.objects.get(title="The Hobbit") # or python style book = await Book.objects.get(Book.title == "The Hobbit") book2 = await Book.objects.first() # first() fetch the instance with lower primary key value assert book == book2 # you can access all fields on loaded model assert book.title == "The Hobbit" assert book.year == 1937 # when no condition is passed to get() # it behaves as last() based on primary key column book3 = await Book.objects.get() assert book3.title == "The Tower of Fools" # When you have a relation, ormar always defines a related model for you # even when all you loaded is a foreign key value like in this example assert isinstance(book.author, Author) # primary key is populated from foreign key stored in books table assert book.author.pk == 1 # since the related model was not loaded all other fields are None assert book.author.name is None # Load the relationship from the database when you already have the related model # alternatively see joins section below await book.author.load() assert book.author.name == "J.R.R. Tolkien" # get all rows for given model authors = await Author.objects.all() assert len(authors) == 2 # to read more about reading data from the database # visit: https://collerek.github.io/ormar/queries/read/ ``` -------------------------------- ### Define User and Role Models for Relation Example Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/raw-data.md Define the User and Role ORM models, including a ManyToMany relationship, to demonstrate fetching related data. ```python # declare models class User(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) class Role(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) users: list[User] = ormar.ManyToMany(User) ``` -------------------------------- ### QuerySet.get / first / all Source: https://context7.com/ormar-orm/ormar/llms.txt Provides methods for retrieving data from the database. `get()` retrieves a single row, `first()` retrieves the row with the lowest primary key, and `all()` retrieves all rows. ```APIDOC ## QuerySet.get / first / all — Read Rows `get()` returns one row (raises `NoMatch` if missing, `MultipleMatches` if ambiguous). `first()` returns the row with the lowest pk. `all()` returns a list. ### Methods - `get(**kwargs) -> Model`: Retrieves a single model instance matching the provided criteria. - `first() -> Optional[Model]`: Retrieves the first model instance based on the lowest primary key. - `all() -> list[Model]`: Retrieves all model instances. - `get_or_none(**kwargs) -> Optional[Model]`: Retrieves a single model instance or `None` if not found. - `iterate() -> AsyncGenerator[Model, None]`: Returns an async generator for iterating over results, useful for large datasets. ### Parameters for `get` and `get_or_none` `**kwargs`: Field lookups to filter the query. ### Returns - `Model`: The retrieved model instance. - `Optional[Model]`: `None` if no matching record is found (for `get_or_none` and `first`). - `list[Model]`: A list of all model instances (for `all`). ### Request Example ```python # Get a specific album album = await Album.objects.get(name="Kind of Blue") # Get the first album first_album = await Album.objects.first() # Get all albums all_albums = await Album.objects.all() # Get an album or None if it doesn't exist missing_album = await Album.objects.get_or_none(name="Nonexistent") ``` ### Response Example ```python # album object # first_album object # all_albums list of album objects # missing_album is None ``` ``` -------------------------------- ### Database Creation with SQLAlchemy Engine Source: https://github.com/ormar-orm/ormar/blob/master/README.md Creates the database engine using SQLAlchemy and then uses the Ormar metadata to create all defined tables. This is typically done once during application setup. ```python engine = sqlalchemy.create_engine(DATABASE_URL.replace('+aiosqlite', '')) base_ormar_config.metadata.create_all(engine) ``` -------------------------------- ### Django Style Ordering Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/filter-and-sort.md Order query results by a specific field using Django style syntax. This example demonstrates ordering by the 'name' field and asserting the order and associated owner. ```python toys = await Toy.objects.select_related("owner").order_by("name").all() assert [x.name.replace("Toy ", "") for x in toys] == [ str(x + 1) for x in range(6) ] assert toys[0].owner == zeus assert toys[1].owner == aphrodite ``` -------------------------------- ### Configure Context with Table Exclusion Source: https://github.com/ormar-orm/ormar/blob/master/docs/models/migrations.md Pass the custom `include_object` function to `context.configure` to apply the table exclusion logic during migration setup. This can be used in both online and offline migration modes. ```python context.configure( url=URL, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, user_module_prefix='sa.', include_object=include_object ) ``` -------------------------------- ### Define Table Exclusion Logic Source: https://github.com/ormar-orm/ormar/blob/master/docs/models/migrations.md Create a function that returns True or False for each object to determine if it should be included in the migration. This example excludes tables starting with 'data_' unless they are 'data_jobs'. ```python def include_object(object, name, type_, reflected, compare_to): if name and name.startswith('data_') and name not in ['data_jobs']: return False return True ``` -------------------------------- ### Create a Model Instance and Save Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/create.md Demonstrates creating a model instance and then saving it to the database using the save() method. ```python class Album(ormar.Model): ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, tablename="album" ) id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) ``` ```python malibu = Album(name="Malibu") await malibu.save() ``` -------------------------------- ### Define Ormar Models and Setup Database Source: https://github.com/ormar-orm/ormar/blob/master/docs/index.md Demonstrates how to define Ormar models (Author and Book) with type hints and relationships, and includes an asynchronous function to set up the database by dropping and creating all tables. This is useful for testing and basic applications. ```python from typing import Optional import ormar import pydantic import sqlalchemy DATABASE_URL = "sqlite+aiosqlite:///db.sqlite" # note that this step is optional -> all ormar cares is an individual # OrmarConfig for each of the models, but this way you do not # have to repeat the same parameters if you use only one database base_ormar_config = ormar.OrmarConfig( database=ormar.DatabaseConnection(DATABASE_URL), metadata=sqlalchemy.MetaData(), ) # Note that all type hints are optional # below is a perfectly valid model declaration # class Author(ormar.Model): # ormar_config = base_ormar_config.copy(tablename="authors") # # id = ormar.Integer(primary_key=True) # <= notice no field types # name = ormar.String(max_length=100) class Author(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) class Book(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) author: Optional[Author] = ormar.ForeignKey(Author) title: str = ormar.String(max_length=100) year: int = ormar.Integer(nullable=True) # note - normally import should be at the beginning of the file import asyncio async def setup_database(): """Create all tables in the database.""" if not base_ormar_config.database.is_connected: await base_ormar_config.database.connect() async with base_ormar_config.database.engine.begin() as conn: await conn.run_sync(base_ormar_config.metadata.drop_all) await conn.run_sync(base_ormar_config.metadata.create_all) if base_ormar_config.database.is_connected: await base_ormar_config.database.disconnect() # create the database # note that in production you should use migrations # note that this is not required if you connect to existing database # just to be sure we clear the db before asyncio.run(setup_database()) ``` -------------------------------- ### Ormar 0.8.0 Breaking Change: First() and Get() Behavior Source: https://github.com/ormar-orm/ormar/blob/master/docs/releases.md The behavior of `first()` and `get()` methods has changed. `first()` now fetches the first row ordered by primary key ascending, while `get()` without filters fetches the first row ordered by primary key descending. ```python # Previously fetched the first row inserted. # Now fetches the first row ordered by primary key asc. await User.objects.first() ``` ```python # Previously fetched the first row inserted. # Now fetches the first row ordered by primary key desc. await User.objects.get() ``` -------------------------------- ### Building Documentation with MkDocs Source: https://github.com/ormar-orm/ormar/blob/master/docs/contributing.md Build the project documentation locally using mkdocs. This is useful for verifying documentation changes before committing. ```bash # 6. Build documentation mkdocs build # if you have changed the documentation make sure it builds successfully # you can also use `mkdocs serve` to serve the documentation at localhost:8000 ``` -------------------------------- ### Model Initialization and Saving Source: https://github.com/ormar-orm/ormar/blob/master/docs/models/index.md Demonstrates initializing a model instance as a normal class and then calling `save()` to persist it to the database. This is suitable when you plan to modify the instance later. ```python --8<-- "../docs_src/models/docs007.py" ``` -------------------------------- ### QuerysetProxy get Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/filter-and-sort.md Allows retrieving the first related object matching criteria from the other side of a relation, working similarly to the main `get` function. ```APIDOC #### get Works exactly the same as [get](./#get) function above but allows you to filter related objects from other side of the relation. !!!tip To read more about `QuerysetProxy` visit [querysetproxy][querysetproxy] section ``` -------------------------------- ### Create Sample Data with User Link Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/raw-data.md Create sample User, Role, and Category data, establishing a link between User and Category via the created_by field. ```python creator = await User(name="Anonymous").save() admin = await Role(name="admin").save() editor = await Role(name="editor").save() await creator.roles.add(admin) await creator.roles.add(editor) news = await Category(name="News", sort_order=0, created_by=creator).save() ``` -------------------------------- ### Initialize Ormar Configuration and Database Connection Source: https://github.com/ormar-orm/ormar/blob/master/docs/index.md Sets up the necessary imports and configuration for Ormar, including the database URL and metadata. This is a foundational step for using Ormar models. ```python # note this is just a partial snippet full working example below # 1. Imports import sqlalchemy import ormar from ormar import DatabaseConnection # 2. Initialization DATABASE_URL = "sqlite+aiosqlite:///db.sqlite" base_ormar_config = ormar.OrmarConfig( metadata=sqlalchemy.MetaData(), database=DatabaseConnection(DATABASE_URL), ) # Define models here # 3. Database creation and tables creation engine = sqlalchemy.create_engine(DATABASE_URL.replace('+aiosqlite', '')) base_ormar_config.metadata.create_all(engine) ``` -------------------------------- ### Asynchronous Database Setup Function Source: https://github.com/ormar-orm/ormar/blob/master/README.md Defines an asynchronous function to set up the database by connecting, dropping existing tables, and creating new ones based on the metadata. Ensures the database is in a clean state before use. ```python async def setup_database(): """Create all tables in the database.""" if not base_ormar_config.database.is_connected: await base_ormar_config.database.connect() async with base_ormar_config.database.engine.begin() as conn: await conn.run_sync(base_ormar_config.metadata.drop_all) await conn.run_sync(base_ormar_config.metadata.create_all) if base_ormar_config.database.is_connected: await base_ormar_config.database.disconnect() # create the database # note that in production you should use migrations # note that this is not required if you connect to existing database # just to be sure we clear the db before asyncio.run(setup_database()) ``` -------------------------------- ### Define Encrypted Field with Fernet Backend (Integer Example) Source: https://github.com/ormar-orm/ormar/blob/master/docs/fields/encryption.md Example of encrypting an integer field using the FERNET backend. Values are encrypted to the database and decrypted on retrieval. ```python ... # rest of model definition year: int = ormar.Integer(encrypt_secret="secret123", encrypt_backend=ormar.EncryptBackends.FERNET) ``` -------------------------------- ### Alembic Initialization and Migration Source: https://github.com/ormar-orm/ormar/blob/master/docs/models/migrations.md Commands to initialize Alembic in your project, generate a new migration script with autogenerate, and apply the migrations. ```bash alembic init alembic alembic revision --autogenerate -m "made some changes" alembic upgrade head ``` -------------------------------- ### Get a single related model Source: https://github.com/ormar-orm/ormar/blob/master/docs/relations/queryset-proxy.md Use `get(**kwargs)` to retrieve a single related model instance based on provided keyword arguments. This method also modifies the parent model's relation list in place to contain only the retrieved model. ```python assert news == await post.categories.get(name="News") # note that method returns the category so you can grab this value # but it also modifies list of related models in place # so regardless of what was previously loaded on parent model # now it has only one value -> just loaded with get() call assert len(post.categories) == 1 assert post.categories[0] == news ``` -------------------------------- ### Get a single record by criteria Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/read.md Use `get` to retrieve a single row matching the criteria. If no row matches, `NoMatch` is raised. If multiple rows match, `MultipleMatches` is raised. Without criteria, it returns the last row sorted by primary key. ```python class Track(ormar.Model): ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, tablename="track" ) id: int = ormar.Integer(primary_key=True) album: Optional[Album] = ormar.ForeignKey(Album) name: str = ormar.String(max_length=100) position: int = ormar.Integer() ``` ```python track = await Track.objects.get(name='The Bird') # note that above is equivalent to await Track.objects.filter(name='The Bird').get() track2 = track = await Track.objects.get() track == track2 # True since it's the only row in db in our example # and get without arguments return first row by pk column desc ``` -------------------------------- ### Get or create a record Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/read.md Use `get_or_create` to retrieve a row by criteria, or create it if it doesn't exist. It returns a tuple containing the model instance and a boolean indicating if it was created. Concurrent calls are handled by falling back to a second `get` if a unique constraint is tripped during creation. ```python class Album(ormar.Model): ormar_config = base_ormar_config.copy(tablename="album") id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) year: int = ormar.Integer() ``` ```python album, created = await Album.objects.get_or_create(name='The Cat', _defaults={"year": 1999}) assert created is True assert album.name == "The Cat" assert album.year == 1999 # object is created as it does not exist album2, created = await Album.objects.get_or_create(name='The Cat') assert created is False assert album == album2 # return True as the same db row is returned ``` -------------------------------- ### Get Item by ID Source: https://context7.com/ormar-orm/ormar/llms.txt Retrieves a specific item by its ID, including its associated category. ```APIDOC ## GET /items/{item_id} ### Description Retrieves a specific item by its ID, including its associated category. ### Method GET ### Endpoint /items/{item_id} ### Parameters #### Path Parameters - **item_id** (int) - Required - The ID of the item to retrieve. ### Response #### Success Response (200) - **item** (Item) - The requested Item object. #### Error Response (404) - **detail** (str) - "Item not found" ### Response Example ```json { "id": 1, "name": "Example Item", "price": 10.99, "category": { "id": 1, "name": "Example Category" } } ``` ``` -------------------------------- ### create Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/create.md Creates a model instance, saves it to the database, and returns the updated model. The allowed keyword arguments are Model field names and their corresponding values. ```APIDOC ## create `create(**kwargs): -> Model` Creates the model instance, saves it in a database and returns the updates model (with pk populated if not passed and autoincrement is set). The allowed kwargs are `Model` fields names and proper value types. ```python class Album(ormar.Model): ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, tablename="album" ) id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) ``` ```python malibu = await Album.objects.create(name="Malibu") await Track.objects.create(album=malibu, title="The Bird", position=1) ``` The alternative is a split creation and persistence of the `Model`. ```python malibu = Album(name="Malibu") await malibu.save() ``` ``` -------------------------------- ### get_or_none Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/read.md Similar to `get`, but returns `None` if no database record matching the criteria is found, instead of raising an exception. ```APIDOC ## get_or_none ### Description Exact equivalent of get described above but instead of raising the exception returns `None` if no db record matching the criteria is found. ``` -------------------------------- ### Create a Model Instance Directly Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/create.md Creates a model instance and saves it to the database in a single step using the create() method. This is useful for creating new records. ```python malibu = await Album.objects.create(name="Malibu") await Track.objects.create(album=malibu, title="The Bird", position=1) ``` -------------------------------- ### Sample Alembic env.py for Ormar Source: https://github.com/ormar-orm/ormar/blob/master/docs/models/migrations.md A sample `env.py` file for Alembic, configured to work with Ormar models. It includes setup for running migrations both online and offline, and specifies how to link Ormar's metadata. ```python from logging.config import fileConfig from sqlalchemy import create_engine from alembic import context import sys, os # add app folder to system path (alternative is running it from parent folder with python -m ...) myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../../') # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) # add your model's MetaData object here (the one used in ormar) # for 'autogenerate' support from app.models.my_models import metadata target_metadata = metadata # set your url here or import from settings # note that by default url is in saved sqlachemy.url variable in alembic.ini file URL = "sqlite:///test.db" def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ context.configure( url=URL, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, # if you use UUID field set also this param # the prefix has to match sqlalchemy import name in alembic # that can be set by sqlalchemy_module_prefix option (default 'sa.') user_module_prefix='sa.' ) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = create_engine(URL) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, # if you use UUID field set also this param # the prefix has to match sqlalchemy import name in alembic # that can be set by sqlalchemy_module_prefix option (default 'sa.') user_module_prefix='sa.' ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online() ``` -------------------------------- ### Aggregations in Ormar Source: https://github.com/ormar-orm/ormar/blob/master/README.md Provides examples of using aggregation functions such as count(), exists(), max(), and min() to perform calculations on querysets. ```python assert 2 == await Author.objects.count() ``` ```python assert await Book.objects.filter(title="The Hobbit").exists() ``` ```python assert 1990 == await Book.objects.max(columns=["year"]) ``` ```python assert 1937 == await Book.objects.min(columns=["year"]) ``` -------------------------------- ### Create Tables Using a Sync Engine Source: https://github.com/ormar-orm/ormar/blob/master/docs/migration.md When creating tables with `metadata.create_all()`, use a synchronous SQLAlchemy engine. Asynchronous engines do not support this operation. ```python import sqlalchemy from ormar import DatabaseConnection DATABASE_URL = "sqlite+aiosqlite:///db.sqlite" database = DatabaseConnection(DATABASE_URL) metadata = sqlalchemy.MetaData() # Create a sync engine for table creation sync_engine = sqlalchemy.create_engine( DATABASE_URL.replace('+aiosqlite', '') ) metadata.create_all(sync_engine) ``` -------------------------------- ### Create Sample ManyToMany Data Source: https://github.com/ormar-orm/ormar/blob/master/docs/relations/many-to-many.md Creates sample Author, Post, and Category instances and establishes a ManyToMany relationship between Post and Category. ```Python guido = await Author.objects.create(first_name="Guido", last_name="Van Rossum") post = await Post.objects.create(title="Hello, M2M", author=guido) news = await Category.objects.create(name="News") ``` -------------------------------- ### Model Definitions for Ormar Source: https://github.com/ormar-orm/ormar/blob/master/docs/queries/filter-and-sort.md Defines the Author and Book models used in the filtering examples. Ensure these models are set up before running queries. ```python base_ormar_config = ormar.OrmarConfig( database=DatabaseConnection(DATABASE_URL), metadata=sqlalchemy.MetaData(), ) class Author(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) class Book(ormar.Model): ormar_config = base_ormar_config.copy() id: int = ormar.Integer(primary_key=True) author: Optional[Author] = ormar.ForeignKey(Author) title: str = ormar.String(max_length=100) year: int = ormar.Integer(nullable=True) ``` -------------------------------- ### Create All Database Tables Source: https://github.com/ormar-orm/ormar/blob/master/docs/models/migrations.md Use this to create all tables defined in your metadata. Ensure the metadata object is the same one used in your Ormar models. ```python import sqlalchemy # get your database url in sqlalchemy format - same as used with DatabaseConnection in Model definition engine = sqlalchemy.create_engine("sqlite:///test.db") # note that this has to be the same metadata that is used in ormar Models definition metadata.create_all(engine) ``` -------------------------------- ### Inheriting from Multiple Models Source: https://github.com/ormar-orm/ormar/blob/master/docs/models/inheritance.md Combine settings and fields from multiple base classes by inheriting from them. This example shows inheriting from DateFieldsModel and AuditModel. ```python class Category(DateFieldsModel, AuditModel): ormar_config = base_ormar_config.copy(tablename="categories") id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=50, unique=True, index=True) code: int = ormar.Integer() ```