This section provides a comprehensive reference for all OxenORM APIs.
The base class for all OxenORM models.
Class Definition
class Model:
"""Base class for all OxenORM models."""
class Meta:
table_name: str = None
db_table: str = None
abstract: bool = False
constraints: List[str] = []
indexes: List[str] = []Meta Options
table_name: Custom table name for the modeldb_table: Alias for table_name (deprecated)abstract: If True, model won't create a tableconstraints: List of table-level constraintsindexes: List of table-level indexes
Methods
# Create operations
@classmethod
async def create(cls, **kwargs) -> Model
@classmethod
async def bulk_create(cls, objects_data: List[Dict]) -> List[Model]
# Read operations
@classmethod
async def all(cls, using_db=None) -> List[Model]
@classmethod
async def get(cls, **kwargs) -> Model
@classmethod
async def get_or_none(cls, **kwargs) -> Optional[Model]
@classmethod
async def filter(cls, *args, **kwargs) -> QuerySet
# Update operations
async def update(self, **kwargs) -> None
async def save(self, force_insert=False, force_update=False) -> None
# Delete operations
async def delete(self) -> None
@classmethod
async def bulk_update(cls, objects: List[Model], fields: List[str]) -> NoneRepresents a database query that can be chained and executed.
Class Definition
class QuerySet:
"""Represents a database query."""
def __init__(self, model_class, db=None)Methods
# Filtering
def filter(self, *args, **kwargs) -> QuerySet
def exclude(self, *args, **kwargs) -> QuerySet
# Ordering
def order_by(self, *fields) -> QuerySet
def reverse(self) -> QuerySet
# Limiting
def limit(self, limit: int) -> QuerySet
def offset(self, offset: int) -> QuerySet
# Aggregations
def count(self) -> int
def aggregate(self, *aggregations) -> Dict
def group_by(self, *fields) -> QuerySet
# Window functions
def window(self, *window_functions) -> QuerySet
# CTEs
def with_cte(self, *ctes) -> QuerySet
# Related objects
def select_related(self, *fields) -> QuerySet
def prefetch_related(self, *fields) -> QuerySet
def only(self, *fields) -> QuerySet
def defer(self, *fields) -> QuerySet
# Execution
async def _execute(self) -> List[Model]
async def first(self) -> Optional[Model]
async def last(self) -> Optional[Model]
# Update and delete
async def update(self, **kwargs) -> int
async def delete(self) -> int
# Streaming
def stream(self) -> AsyncIterator[Model]Represents a database query condition.
Class Definition
class Q:
"""Represents a database query condition."""
def __init__(self, **kwargs)
def __and__(self, other) -> Q
def __or__(self, other) -> Q
def __invert__(self) -> QUsage Examples
from oxen import Q
# Simple condition
Q(name="John")
# Complex condition
Q(age__gte=18) & Q(is_active=True)
# OR condition
Q(age__lt=18) | Q(age__gt=65)
# NOT condition
~Q(is_active=False)A field for storing character data.
class CharField(Field):
def __init__(self, max_length: int = None, **kwargs)Parameters
max_length: Maximum length of the stringunique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing large text data.
class TextField(Field):
def __init__(self, **kwargs)Parameters
unique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing integer values.
class IntegerField(Field):
def __init__(self, **kwargs)Parameters
unique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexauto_increment: If True, auto-increment fieldhelp_text: Help text for the field
A field for storing floating-point values.
class FloatField(Field):
def __init__(self, **kwargs)Parameters
unique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing boolean values.
class BooleanField(Field):
def __init__(self, **kwargs)Parameters
unique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing date and time values.
class DateTimeField(Field):
def __init__(self, auto_now=False, auto_now_add=False, **kwargs)Parameters
auto_now: If True, update field on every saveauto_now_add: If True, set field on creation onlyunique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing date values.
class DateField(Field):
def __init__(self, **kwargs)Parameters
unique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing time values.
class TimeField(Field):
def __init__(self, **kwargs)Parameters
unique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing UUID values.
class UUIDField(Field):
def __init__(self, primary_key=False, **kwargs)Parameters
primary_key: If True, use as primary keyunique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing JSON data.
class JSONField(Field):
def __init__(self, **kwargs)Parameters
unique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing email addresses.
class EmailField(Field):
def __init__(self, max_length=254, **kwargs)Parameters
max_length: Maximum length of the emailunique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing URLs.
class URLField(Field):
def __init__(self, max_length=200, **kwargs)Parameters
max_length: Maximum length of the URLunique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing file paths.
class FileField(Field):
def __init__(self, upload_to="", **kwargs)Parameters
upload_to: Directory to upload files tounique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing image file paths.
class ImageField(FileField):
def __init__(self, upload_to="", **kwargs)Parameters
upload_to: Directory to upload images tounique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for storing arrays (PostgreSQL only).
class ArrayField(Field):
def __init__(self, base_field, **kwargs)Parameters
base_field: Field type for array elementsunique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for creating foreign key relationships.
class ForeignKeyField(RelationalField):
def __init__(self, to, related_name=None, on_delete=None, **kwargs)Parameters
to: Target model classrelated_name: Name for reverse relationshipon_delete: Action on delete (CASCADE, SET_NULL, etc.)unique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for creating one-to-one relationships.
class OneToOneField(RelationalField):
def __init__(self, to, related_name=None, on_delete=None, **kwargs)Parameters
to: Target model classrelated_name: Name for reverse relationshipon_delete: Action on delete (CASCADE, SET_NULL, etc.)unique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
A field for creating many-to-many relationships.
class ManyToManyField(RelationalField):
def __init__(self, to, through=None, related_name=None, **kwargs)Parameters
to: Target model classthrough: Intermediate model for custom relationshipsrelated_name: Name for reverse relationshipunique: If True, field must be uniquenull: If True, field can be NULLdefault: Default value for the fielddb_index: If True, create database indexhelp_text: Help text for the field
Count the number of objects.
class Count(Aggregation):
def __init__(self, field="*", distinct=False)Parameters
field: Field to count (default: "*")distinct: If True, count distinct values
Sum the values of a field.
class Sum(Aggregation):
def __init__(self, field)Parameters
field: Field to sum
Calculate the average of a field.
class Avg(Aggregation):
def __init__(self, field)Parameters
field: Field to average
Find the maximum value of a field.
class Max(Aggregation):
def __init__(self, field)Parameters
field: Field to find maximum of
Find the minimum value of a field.
class Min(Aggregation):
def __init__(self, field)Parameters
field: Field to find minimum of
Add row numbers to results.
class RowNumber(WindowFunction):
def __init__(self):
super().__init__("ROW_NUMBER")Add rank to results.
class Rank(WindowFunction):
def __init__(self):
super().__init__("RANK")Add dense rank to results.
class DenseRank(WindowFunction):
def __init__(self):
super().__init__("DENSE_RANK")Get value from previous row.
class Lag(WindowFunction):
def __init__(self, field, offset=1):
super().__init__("LAG", field, offset)Parameters
field: Field to lagoffset: Number of rows to lag
Get value from next row.
class Lead(WindowFunction):
def __init__(self, field, offset=1):
super().__init__("LEAD", field, offset)Parameters
field: Field to leadoffset: Number of rows to lead
Create a common table expression.
class CommonTableExpression:
def __init__(self, name, query, recursive=False)Parameters
name: Name of the CTEquery: QuerySet for the CTErecursive: If True, create recursive CTE
Connect to a database.
async def connect(url: str, **kwargs) -> NoneParameters
url: Database connection URL**kwargs: Additional connection parameters
Supported URLs
- SQLite:
sqlite:///path/to/database.db - PostgreSQL:
postgresql://user:pass@host:port/database - MySQL:
mysql://user:pass@host:port/database
Disconnect from the database.
async def disconnect() -> NoneSet the database connection for all models.
def set_database_for_models(database) -> NoneParameters
database: Database connection object
Create a database transaction.
async def transaction() -> TransactionUsage
async with transaction() as txn:
# Database operations
await txn.commit()Represents a database transaction.
Methods
async def commit(self) -> None
async def rollback(self) -> NoneSignal sent before saving a model.
pre_save = Signal()Signal sent after saving a model.
post_save = Signal()Signal sent before deleting a model.
pre_delete = Signal()Signal sent after deleting a model.
post_delete = Signal()Usage
from oxen import pre_save, post_save
@pre_save.connect
async def handle_pre_save(sender, instance, **kwargs):
print(f"About to save {instance}")
@post_save.connect
async def handle_post_save(sender, instance, created, **kwargs):
print(f"Saved {instance}, created: {created}")Engine for managing database migrations.
class MigrationEngine:
def __init__(self, database_url: str)Methods
async def create_migrations_table(self) -> None
async def get_applied_migrations(self) -> List[str]
async def apply_migration(self, migration_file: str) -> None
async def rollback_migration(self, migration_file: str) -> NoneGenerator for creating migration files.
class MigrationGenerator:
def __init__(self, models: List[Type[Model]])Methods
def generate_migration(self, name: str) -> str
def get_sql_statements(self) -> List[str]Runner for executing migrations.
class MigrationRunner:
def __init__(self, database_url: str)Methods
async def run_migrations(self, migration_dir: str) -> None
async def rollback_migrations(self, migration_dir: str, steps: int = 1) -> None
async def get_migration_status(self, migration_dir: str) -> DictOptimizer for analyzing and improving query performance.
class QueryOptimizer:
def __init__(self)Methods
async def analyze_query(self, queryset: QuerySet) -> QueryPlan
async def get_suggestions(self, queryset: QuerySet) -> List[str]
async def optimize_query(self, queryset: QuerySet) -> QuerySetDashboard for monitoring database performance.
class MonitoringDashboard:
def __init__(self)Methods
async def get_metrics(self) -> Dict[str, Any]
async def get_alerts(self) -> List[Alert]
async def add_alert(self, alert: Alert) -> None
async def export_data(self) -> Dict[str, Any]Interface for managing database schemas and models.
class AdminInterface:
def __init__(self)Methods
def register_models(self, models: List[Type[Model]]) -> None
def get_schema_summary(self) -> Dict[str, Any]
def get_table_details(self, table_name: str) -> Optional[Dict[str, Any]]
def generate_schema_diagram(self) -> Dict[str, Any]
def export_schema_json(self, filename: str) -> NoneRunner for performance benchmarking.
class BenchmarkRunner:
def __init__(self)Methods
def create_suite(self, name: str, description: str = "") -> BenchmarkSuite
async def run_benchmark(self, test_name: str, operation: Callable,
iterations: int = 1000, warmup_iterations: int = 100) -> BenchmarkResult
def generate_report(self, suite_name: str) -> Dict[str, Any]
def save_report(self, suite_name: str, filename: Optional[str] = None) -> PathBase exception for all OxenORM errors.
class OxenError(Exception):
passRaised when there's a configuration error.
class ConfigurationError(OxenError):
passRaised when there's a database connection error.
class ConnectionError(OxenError):
passRaised when field validation fails.
class ValidationError(OxenError):
passRaised when database integrity constraints are violated.
class IntegrityError(OxenError):
passRaised when a requested object doesn't exist.
class DoesNotExist(OxenError):
passRaised when multiple objects are returned when only one was expected.
class MultipleObjectsReturned(OxenError):
passRaised when there's a database operation error.
class OperationalError(OxenError):
passRaised when there's a transaction error.
class TransactionError(OxenError):
pass# Initialize database
oxen db init --url <database_url>
# Check database status
oxen db status --url <database_url>
# Create tables
oxen db create-tables --url <database_url># Generate migrations
oxen migrate makemigrations --url <database_url>
# Apply migrations
oxen migrate migrate --url <database_url>
# Check migration status
oxen migrate status --url <database_url>
# Rollback migrations
oxen migrate rollback --url <database_url> --steps <number># Run performance benchmarks
oxen benchmark performance --url <database_url> --iterations <number>
# Generate performance report
oxen benchmark report --output <filename># Start admin interface
oxen admin start --host <host> --port <port>
# Open admin interface in browser
oxen admin open --url <admin_url>