0
# Django Stubs Extensions
1
2
Runtime extensions and monkey-patching functionality for the django-stubs type stubs package. This package enables advanced typing features for Django framework classes that cannot be implemented through static type stubs alone, providing runtime support for generic Django classes and comprehensive type annotations.
3
4
## Package Information
5
6
- **Package Name**: django-stubs-ext
7
- **Language**: Python
8
- **Installation**: `pip install django-stubs-ext`
9
- **Dependencies**: `django`, `typing-extensions`
10
- **Python Support**: 3.8+
11
- **Django Support**: 3.2, 4.1, 4.2
12
13
## Core Imports
14
15
```python
16
import django_stubs_ext
17
```
18
19
Specific functionality:
20
21
```python
22
from django_stubs_ext import monkeypatch
23
from django_stubs_ext import QuerySetAny, ValuesQuerySet, WithAnnotations, Annotations
24
from django_stubs_ext import AnyAttrAllowed, StrPromise, StrOrPromise
25
```
26
27
## Basic Usage
28
29
```python
30
import django_stubs_ext
31
32
# Apply monkey-patches once in your Django settings
33
django_stubs_ext.monkeypatch()
34
35
# Use type aliases for better type checking
36
from django_stubs_ext import QuerySetAny, WithAnnotations
37
from django.db import models
38
from django.db.models import Count, Case, When
39
from typing import TypedDict
40
41
# Example model with annotations
42
class User(models.Model):
43
name = models.CharField(max_length=100)
44
email = models.EmailField()
45
last_login = models.DateTimeField(null=True, blank=True)
46
47
class UserStats(TypedDict):
48
count: int
49
active: bool
50
51
# Type-annotated QuerySet with custom annotations
52
annotated_queryset: WithAnnotations[User, UserStats] = User.objects.annotate(
53
count=Count('id'),
54
active=Case(When(last_login__isnull=False, then=True), default=False)
55
)
56
```
57
58
## Architecture
59
60
The package consists of three main components:
61
62
- **Monkey-patching System**: Dynamically adds `__class_getitem__` methods to Django classes that need generic type support
63
- **Type Aliases**: Provides specialized QuerySet and string type aliases for improved type checking
64
- **Annotation Support**: Offers typed containers for model annotations and typed base classes for Django components
65
66
The monkey-patching system is version-aware, automatically detecting the Django version at runtime and applying only the necessary patches to ensure compatibility across multiple Django versions.
67
68
## Capabilities
69
70
### Runtime Monkey-Patching
71
72
Core functionality for patching Django generic classes to support type parameterization. This enables proper type checking for Django classes that don't natively support generic syntax.
73
74
```python { .api }
75
def monkeypatch(
76
extra_classes: Optional[Iterable[type]] = None,
77
include_builtins: bool = True
78
) -> None:
79
"""Apply runtime monkey-patches to Django classes for generic type support."""
80
```
81
82
[Monkey-Patching](./monkey-patching.md)
83
84
### QuerySet Type Aliases
85
86
Specialized type aliases for Django QuerySets that provide better type safety and IDE support when working with query results and values() calls.
87
88
```python { .api }
89
QuerySetAny = QuerySet # Type alias for generic QuerySet with any model
90
ValuesQuerySet = QuerySet # Type alias for QuerySet with values() calls
91
```
92
93
[QuerySet Types](./queryset-types.md)
94
95
### Model Annotations
96
97
Type-safe containers and annotations for Django model annotations, enabling proper typing of models with computed fields and aggregations.
98
99
```python { .api }
100
class Annotations[_Annotations]:
101
"""Generic container for TypedDict-style model annotations."""
102
103
WithAnnotations = Annotated[_T, Annotations[_Annotations]]
104
"""Annotated type combining Django models with their annotation types."""
105
```
106
107
[Model Annotations](./model-annotations.md)
108
109
### String Type Handling
110
111
Type aliases for Django's Promise-based string handling system, providing proper type safety for lazy string evaluation and internationalization.
112
113
```python { .api }
114
StrPromise = Promise # Django Promise string type
115
StrOrPromise = Union[str, StrPromise] # Union of str and Promise types
116
```
117
118
[String Types](./string-types.md)
119
120
### Protocol Definitions
121
122
Protocol definitions for flexible attribute access and typed base classes for Django components like Model.Meta and database routers.
123
124
```python { .api }
125
class AnyAttrAllowed(Protocol):
126
"""Protocol for classes allowing arbitrary attribute access."""
127
def __getattr__(self, item: str) -> Any: ...
128
def __setattr__(self, item: str, value: Any) -> None: ...
129
```
130
131
[Protocols and Base Classes](./protocols.md)
132
133
## Types
134
135
```python { .api }
136
from typing import Any, Generic, Iterable, Mapping, Optional, Protocol, TypeVar, Union
137
from typing_extensions import Annotated
138
from django.db.models.base import Model
139
140
_T = TypeVar("_T", bound=Model)
141
_Annotations = TypeVar("_Annotations", covariant=True, bound=Mapping[str, Any])
142
```