CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-stubs

Comprehensive type stubs for Django framework enabling static type checking with mypy

Pending
Overview
Eval results
Files

database-orm.mddocs/

Database and ORM

Django's Object-Relational Mapping (ORM) system provides a Python interface for database operations, enabling type-safe database queries, model definitions, and relationship management.

Core Imports

# Model base class and fields
from django.db import models
from django.db.models import Model, Manager, QuerySet

# Field types
from django.db.models import (
    CharField, TextField, IntegerField, PositiveIntegerField,
    FloatField, DecimalField, BooleanField, DateField, DateTimeField,
    TimeField, EmailField, URLField, SlugField, UUIDField,
    ForeignKey, OneToOneField, ManyToManyField,
    FileField, ImageField, JSONField
)

# Query functions and aggregation
from django.db.models import (
    Q, F, Value, Count, Sum, Avg, Max, Min,
    Exists, OuterRef, Subquery, Case, When
)

# Database operations
from django.db import transaction, connection
from django.db.models.signals import pre_save, post_save, pre_delete, post_delete

Capabilities

Model Base Class

The fundamental base class for all Django models, providing database table mapping and ORM functionality.

class Model:
    """
    Base class for all Django models.
    
    Provides database table mapping, field definitions, and ORM methods.
    """
    pk: Any  # Primary key field
    objects: Manager  # Default manager
    
    def save(self, force_insert: bool = False, force_update: bool = False, using: str = None, update_fields: list = None) -> None: ...
    def delete(self, using: str = None, keep_parents: bool = False) -> tuple: ...
    def refresh_from_db(self, using: str = None, fields: list = None) -> None: ...
    def clean(self) -> None: ...
    def full_clean(self, exclude: list = None, validate_unique: bool = True) -> None: ...
    def validate_unique(self, exclude: list = None) -> None: ...
    
    @classmethod
    def from_db(cls, db: str, field_names: list, values: list): ...

Manager and QuerySet

Database query interface providing lazy evaluation and chainable query operations.

class Manager:
    """
    Default manager for model database operations.
    """
    def get_queryset(self) -> QuerySet: ...
    def all(self) -> QuerySet: ...
    def filter(self, *args, **kwargs) -> QuerySet: ...
    def exclude(self, *args, **kwargs) -> QuerySet: ...
    def get(self, *args, **kwargs): ...
    def create(self, **kwargs): ...
    def get_or_create(self, defaults: dict = None, **kwargs) -> tuple: ...
    def update_or_create(self, defaults: dict = None, **kwargs) -> tuple: ...
    def bulk_create(self, objs: list, batch_size: int = None, ignore_conflicts: bool = False, update_conflicts: bool = False, update_fields: list = None, unique_fields: list = None) -> list: ...
    def bulk_update(self, objs: list, fields: list, batch_size: int = None) -> int: ...
    def count(self) -> int: ...
    def exists(self) -> bool: ...
    def delete(self) -> tuple: ...
    def update(self, **kwargs) -> int: ...

class QuerySet:
    """
    Lazy database query object supporting chaining and evaluation.
    """
    def filter(self, *args, **kwargs) -> QuerySet: ...
    def exclude(self, *args, **kwargs) -> QuerySet: ...
    def annotate(self, *args, **kwargs) -> QuerySet: ...
    def order_by(self, *field_names) -> QuerySet: ...
    def reverse(self) -> QuerySet: ...
    def distinct(self, *field_names) -> QuerySet: ...
    def values(self, *fields) -> QuerySet: ...
    def values_list(self, *fields, flat: bool = False, named: bool = False) -> QuerySet: ...
    def select_related(self, *fields) -> QuerySet: ...
    def prefetch_related(self, *lookups) -> QuerySet: ...
    def only(self, *fields) -> QuerySet: ...
    def defer(self, *fields) -> QuerySet: ...
    def aggregate(self, *args, **kwargs) -> dict: ...
    def get(self, *args, **kwargs): ...
    def first(self): ...
    def last(self): ...
    def earliest(self, *fields): ...
    def latest(self, *fields): ...
    def count(self) -> int: ...
    def exists(self) -> bool: ...
    def delete(self) -> tuple: ...
    def update(self, **kwargs) -> int: ...
    def iterator(self, chunk_size: int = 2000): ...

Basic Field Types

Core field types for model definitions with appropriate type annotations.

class Field:
    """Base field class for all model fields."""
    def __init__(self, verbose_name: str = None, name: str = None, primary_key: bool = False, 
                 max_length: int = None, unique: bool = False, blank: bool = False, 
                 null: bool = False, db_index: bool = False, default=None, 
                 editable: bool = True, help_text: str = '', choices=None, **kwargs): ...

class AutoField(Field):
    """Auto-incrementing integer field."""
    def __init__(self, **kwargs): ...

class BigAutoField(Field):
    """64-bit auto-incrementing integer field."""
    def __init__(self, **kwargs): ...

class BigIntegerField(Field):
    """64-bit integer field."""
    def __init__(self, **kwargs): ...

class BinaryField(Field):
    """Binary data field."""
    def __init__(self, max_length: int = None, **kwargs): ...

class BooleanField(Field):
    """Boolean field."""
    def __init__(self, **kwargs): ...

class CharField(Field):
    """Character/string field with maximum length."""
    def __init__(self, max_length: int, **kwargs): ...

class DateField(Field):
    """Date field."""
    def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs): ...

class DateTimeField(Field):
    """Date and time field."""
    def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs): ...

class DecimalField(Field):
    """Decimal number field with fixed precision."""
    def __init__(self, max_digits: int, decimal_places: int, **kwargs): ...

class DurationField(Field):
    """Duration/timedelta field."""
    def __init__(self, **kwargs): ...

class EmailField(CharField):
    """Email address field with validation."""
    def __init__(self, max_length: int = 254, **kwargs): ...

class FileField(Field):
    """File upload field."""
    def __init__(self, upload_to: str = '', storage=None, **kwargs): ...

class FloatField(Field):
    """Floating point number field."""
    def __init__(self, **kwargs): ...

class ImageField(FileField):
    """Image file field with validation."""
    def __init__(self, upload_to: str = '', height_field: str = None, width_field: str = None, **kwargs): ...

class IntegerField(Field):
    """Integer field."""
    def __init__(self, **kwargs): ...

class JSONField(Field):
    """JSON data field."""
    def __init__(self, encoder=None, decoder=None, **kwargs): ...

class PositiveBigIntegerField(Field):
    """Positive 64-bit integer field."""
    def __init__(self, **kwargs): ...

class PositiveIntegerField(Field):
    """Positive integer field."""
    def __init__(self, **kwargs): ...

class PositiveSmallIntegerField(Field):
    """Positive small integer field."""
    def __init__(self, **kwargs): ...

class SlugField(CharField):
    """URL slug field."""
    def __init__(self, max_length: int = 50, **kwargs): ...

class SmallAutoField(Field):
    """Small auto-incrementing integer field."""
    def __init__(self, **kwargs): ...

class SmallIntegerField(Field):
    """Small integer field."""
    def __init__(self, **kwargs): ...

class TextField(Field):
    """Large text field."""
    def __init__(self, **kwargs): ...

class TimeField(Field):
    """Time field."""
    def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs): ...

class URLField(CharField):
    """URL field with validation."""
    def __init__(self, max_length: int = 200, **kwargs): ...

class UUIDField(Field):
    """UUID field."""
    def __init__(self, **kwargs): ...

Relationship Fields

Fields that define relationships between models.

class ForeignKey(Field):
    """Foreign key relationship to another model."""
    def __init__(self, to, on_delete, related_name: str = None, related_query_name: str = None,
                 limit_choices_to=None, parent_link: bool = False, to_field: str = None,
                 db_constraint: bool = True, **kwargs): ...

class ManyToManyField(Field):
    """Many-to-many relationship."""
    def __init__(self, to, related_name: str = None, related_query_name: str = None,
                 limit_choices_to=None, symmetrical: bool = None, through: str = None,
                 through_fields: tuple = None, db_constraint: bool = True,
                 db_table: str = None, **kwargs): ...

class OneToOneField(ForeignKey):
    """One-to-one relationship."""
    def __init__(self, to, on_delete, parent_link: bool = False, **kwargs): ...

class ForeignObject(Field):
    """Generic foreign object for advanced relationships."""
    def __init__(self, to, on_delete, from_fields: list, to_fields: list, **kwargs): ...

Deletion Behaviors

Constants defining behavior when related objects are deleted.

CASCADE: Any  # Delete related objects
PROTECT: Any  # Prevent deletion if related objects exist
RESTRICT: Any  # Restrict deletion  
SET_NULL: Any  # Set foreign key to NULL
SET_DEFAULT: Any  # Set foreign key to default value
DO_NOTHING: Any  # Take no action

class ProtectedError(Exception):
    """Raised when trying to delete a protected object."""

class RestrictedError(Exception):
    """Raised when deletion is restricted."""

Query Expressions

Objects for building complex database queries and expressions.

class Q:
    """Query object for complex lookups."""
    def __init__(self, *args, **kwargs): ...
    def __and__(self, other): ...
    def __or__(self, other): ...
    def __invert__(self): ...

class F:
    """Field reference for database-level operations."""
    def __init__(self, name: str): ...
    def __add__(self, other): ...
    def __sub__(self, other): ...
    def __mul__(self, other): ...
    def __truediv__(self, other): ...
    def __mod__(self, other): ...
    def __pow__(self, other): ...

class Value:
    """Literal value in database expressions."""
    def __init__(self, value, output_field=None): ...

class Case:
    """Conditional database expression."""
    def __init__(self, *cases, default=None, output_field=None): ...

class When:
    """Condition for Case expressions."""
    def __init__(self, condition=None, then=None, **lookups): ...

class Exists:
    """EXISTS subquery expression."""
    def __init__(self, queryset, negated: bool = False): ...

class Subquery:
    """Subquery expression."""
    def __init__(self, queryset, output_field=None): ...

class OuterRef:
    """Reference to outer query in subqueries."""
    def __init__(self, name: str): ...

class Func:
    """Database function call."""
    def __init__(self, *expressions, output_field=None, **extra): ...

class Window:
    """Window function expression."""
    def __init__(self, expression, partition_by=None, order_by=None, frame=None, output_field=None): ...

Aggregates

Functions for aggregating database values.

class Aggregate:
    """Base class for aggregate functions."""
    def __init__(self, *expressions, output_field=None, is_summary: bool = False, **extra): ...

class Avg(Aggregate):
    """Average aggregate function."""

class Count(Aggregate):
    """Count aggregate function."""
    def __init__(self, expression, distinct: bool = False, **extra): ...

class Max(Aggregate):
    """Maximum value aggregate function."""

class Min(Aggregate):
    """Minimum value aggregate function."""

class StdDev(Aggregate):
    """Standard deviation aggregate function."""
    def __init__(self, expression, sample: bool = False, **extra): ...

class Sum(Aggregate):
    """Sum aggregate function."""

class Variance(Aggregate):
    """Variance aggregate function."""
    def __init__(self, expression, sample: bool = False, **extra): ...

Database Constraints

Constraints for ensuring data integrity at the database level.

class BaseConstraint:
    """Base class for database constraints."""
    def __init__(self, name: str): ...

class CheckConstraint(BaseConstraint):
    """Check constraint for validating field values."""
    def __init__(self, check, name: str): ...

class UniqueConstraint(BaseConstraint):
    """Unique constraint across multiple fields."""
    def __init__(self, fields: list, name: str, condition=None, deferrable=None, include=None, opclasses=None): ...

class Deferrable:
    """Deferrable constraint options."""
    DEFERRED: str
    IMMEDIATE: str

Database Indexes

Index definitions for query optimization.

class Index:
    """Database index definition."""
    def __init__(self, fields: list, name: str = None, db_tablespace: str = None, 
                 opclasses: list = None, condition=None, include: list = None): ...

Prefetch Operations

Optimized loading of related objects.

class Prefetch:
    """Prefetch definition for select_related optimization."""
    def __init__(self, lookup: str, queryset=None, to_attr: str = None): ...

def prefetch_related_objects(model_instances: list, *related_lookups) -> None:
    """Prefetch related objects for a list of model instances."""

Database Configuration

Database connection and routing configuration.

connections: ConnectionHandler  # Database connections
connection: BaseDatabaseWrapper  # Default database connection
router: ConnectionRouter  # Database routing

DEFAULT_DB_ALIAS: str  # Default database alias name

def close_old_connections() -> None:
    """Close database connections that have become unusable."""

def reset_queries() -> None:
    """Reset the list of queries logged for the current connection."""

Database Exceptions

Exceptions for database operations and integrity constraints.

class Error(Exception):
    """Base database exception."""

class DatabaseError(Error):
    """Database-related error."""

class DataError(DatabaseError):
    """Data-related database error."""

class IntegrityError(DatabaseError):
    """Database integrity constraint violation."""

class InterfaceError(DatabaseError):
    """Database interface error."""

class InternalError(DatabaseError):
    """Database internal error."""

class NotSupportedError(DatabaseError):
    """Database operation not supported."""

class OperationalError(DatabaseError):
    """Database operational error."""

class ProgrammingError(DatabaseError):
    """Database programming error."""

Model Utilities

Utility functions and constants for model operations.

NOT_PROVIDED: Any  # Sentinel for field defaults

class FieldDoesNotExist(Exception):
    """Raised when accessing non-existent model field."""

def get_object_or_404(klass, *args, **kwargs):
    """Get object or raise Http404 if not found."""

def get_list_or_404(klass, *args, **kwargs):
    """Get object list or raise Http404 if empty."""

Model Meta Options

Configuration options for model behavior and database table settings.

class Options:
    """Model meta options configuration."""
    abstract: bool
    app_label: str
    base_manager_name: str
    db_table: str
    db_tablespace: str
    default_manager_name: str
    default_related_name: str
    get_latest_by: str
    managed: bool
    order_with_respect_to: str
    ordering: list
    permissions: list
    default_permissions: list
    proxy: bool
    required_db_features: list
    required_db_vendor: str
    select_on_save: bool
    indexes: list
    unique_together: list
    index_together: list
    constraints: list
    verbose_name: str
    verbose_name_plural: str

Install with Tessl CLI

npx tessl i tessl/pypi-django-stubs

docs

admin.md

auth.md

contrib.md

database-orm.md

forms.md

http.md

index.md

migrations.md

mypy-plugin.md

signals.md

templates.md

transactions.md

urls.md

views.md

tile.json