Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions django-stubs/db/models/fields/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import ipaddress
import uuid
from collections.abc import Callable, Iterable, Mapping, Sequence
from datetime import date, datetime, time, timedelta
from typing import Any, ClassVar, Generic, Literal, TypeAlias, TypeVar, overload
from typing import Any, ClassVar, Generic, Literal, TypeAlias, overload

from django.core.checks import CheckMessage
from django.core.exceptions import FieldDoesNotExist as FieldDoesNotExist
Expand All @@ -14,7 +14,7 @@ from django.db.models.query_utils import Q, RegisterLookupMixin
from django.forms import Widget
from django.utils.choices import _Choice, _ChoiceNamedGroup, _ChoicesCallable
from django.utils.functional import _StrOrPromise, cached_property
from typing_extensions import Self
from typing_extensions import Self, TypeVar

BLANK_CHOICE_DASH: list[tuple[str, str]] = ...

Expand Down Expand Up @@ -126,7 +126,10 @@ class Field(RegisterLookupMixin, Generic[_ST, _GT]):
def get_attname(self) -> str: ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...

_I = TypeVar("_I", bound=int | None)
# Defaults for _I and _C work around enum choices inference in ty.
# https://github.com/astral-sh/ty/issues/4551
# Include None so bare subclasses still accept nullable defaults.
_I = TypeVar("_I", bound=int | None, default=int | None)

class IntegerField(Field[_I | Combinable, _I], Generic[_I]):
@overload
Expand Down Expand Up @@ -699,7 +702,7 @@ class SmallAutoField(AutoFieldMixin, SmallIntegerField[int]):
error_messages: _ErrorMessagesMapping | None = ...,
) -> Self: ...

_C = TypeVar("_C", bound=str | None)
_C = TypeVar("_C", bound=str | None, default=str | None)

class CharField(Field[_C | Combinable, _C], Generic[_C]):
@overload
Expand Down
30 changes: 18 additions & 12 deletions django-stubs/db/models/query.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ from typing_extensions import Self, TypeVar, override

_T = TypeVar("_T", covariant=True)
_ContainsT = TypeVar("_ContainsT")
# Keep queryset covariance for compatibility with django-stubs. The targeted ty
# ignores in QuerySet preserve model-specific inputs and invariant return types
# where the existing signatures conflict with this covariance.
_Model = TypeVar("_Model", bound=Model, covariant=True)
_Row = TypeVar("_Row", covariant=True, default=_Model) # ONLY use together with _Model
_TupleT = TypeVar("_TupleT", bound=tuple[Any, ...], covariant=True)
Expand Down Expand Up @@ -68,7 +71,7 @@ class QuerySet(AltersData, _SupportsContains[object], Iterable[_Row], Sized, Gen
hints: dict[str, Model] | None = None,
) -> None: ...
@classmethod
def as_manager(cls) -> Manager[_Model]: ...
def as_manager(cls) -> Manager[_Model]: ... # ty: ignore[invalid-generic-class]
def __deepcopy__(self, memo: dict[int, Any]) -> Self: ...
if sys.version_info >= (3, 11):
@override
Expand All @@ -85,11 +88,11 @@ class QuerySet(AltersData, _SupportsContains[object], Iterable[_Row], Sized, Gen
def __getitem__(self, i: int) -> _Row: ...
@overload
def __getitem__(self, s: slice) -> Self: ...
def __class_getitem__(cls, item: type[_Model]) -> Self: ... # pyright: ignore[reportGeneralTypeIssues]
# Technically, the other QuerySet must be of the same type _T, but _T is covariant
def __and__(self, other: QuerySet[_Model, _Row]) -> Self: ...
def __or__(self, other: QuerySet[_Model, _Row]) -> Self: ...
def __xor__(self, other: QuerySet[_Model, _Row]) -> Self: ...
def __class_getitem__(cls, *args: Any, **kwargs: Any) -> type[Self]: ...
# Keep model and row types related across queryset combinations.
def __and__(self, other: QuerySet[_Model, _Row]) -> Self: ... # ty: ignore[invalid-generic-class]
def __or__(self, other: QuerySet[_Model, _Row]) -> Self: ... # ty: ignore[invalid-generic-class]
def __xor__(self, other: QuerySet[_Model, _Row]) -> Self: ... # ty: ignore[invalid-generic-class]
# IMPORTANT: When updating any of the following methods' signatures, please ALSO modify
# the corresponding method in BaseManager.
def iterator(self, chunk_size: int | None = None) -> Iterator[_Row]: ...
Expand All @@ -104,7 +107,7 @@ class QuerySet(AltersData, _SupportsContains[object], Iterable[_Row], Sized, Gen
async def acreate(self, **kwargs: Any) -> _Model: ...
def bulk_create(
self,
objs: Iterable[_Model],
objs: Iterable[_Model], # ty: ignore[invalid-generic-class]
batch_size: int | None = None,
ignore_conflicts: bool = False,
update_conflicts: bool = False,
Expand All @@ -113,16 +116,19 @@ class QuerySet(AltersData, _SupportsContains[object], Iterable[_Row], Sized, Gen
) -> list[_Model]: ...
async def abulk_create(
self,
objs: Iterable[_Model],
objs: Iterable[_Model], # ty: ignore[invalid-generic-class]
batch_size: int | None = None,
ignore_conflicts: bool = False,
update_conflicts: bool = False,
update_fields: Collection[str] | None = None,
unique_fields: Collection[str] | None = None,
) -> list[_Model]: ...
def bulk_update(self, objs: Iterable[_Model], fields: Iterable[str], batch_size: int | None = None) -> int: ...
def bulk_update(self, objs: Iterable[_Model], fields: Iterable[str], batch_size: int | None = None) -> int: ... # ty: ignore[invalid-generic-class]
async def abulk_update(
self, objs: Iterable[_Model], fields: Iterable[str], batch_size: int | None = None
self,
objs: Iterable[_Model], # ty: ignore[invalid-generic-class]
fields: Iterable[str],
batch_size: int | None = None,
) -> int: ...
def get_or_create(self, defaults: Mapping[str, Any] | None = None, **kwargs: Any) -> tuple[_Model, bool]: ...
async def aget_or_create(self, defaults: Mapping[str, Any] | None = None, **kwargs: Any) -> tuple[_Model, bool]: ...
Expand All @@ -146,8 +152,8 @@ class QuerySet(AltersData, _SupportsContains[object], Iterable[_Row], Sized, Gen
async def afirst(self) -> _Row | None: ...
def last(self) -> _Row | None: ...
async def alast(self) -> _Row | None: ...
def in_bulk(self, id_list: Iterable[Any] | None = None, *, field_name: str = "pk") -> dict[Any, _Model]: ...
async def ain_bulk(self, id_list: Iterable[Any] | None = None, *, field_name: str = "pk") -> dict[Any, _Model]: ...
def in_bulk(self, id_list: Iterable[Any] | None = None, *, field_name: str = "pk") -> dict[Any, _Model]: ... # ty: ignore[invalid-generic-class]
async def ain_bulk(self, id_list: Iterable[Any] | None = None, *, field_name: str = "pk") -> dict[Any, _Model]: ... # ty: ignore[invalid-generic-class]
def delete(self) -> tuple[int, dict[str, int]]: ...
async def adelete(self) -> tuple[int, dict[str, int]]: ...
def _raw_delete(self, using: str | None) -> int: ...
Expand Down
44 changes: 44 additions & 0 deletions tests/trout/choices_typing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from django.db import models
from typing_extensions import assert_type


class Status(models.TextChoices):
DRAFT = "draft", "Draft"
PUBLISHED = "published", "Published"


class Priority(models.IntegerChoices):
LOW = 1, "Low"
HIGH = 2, "High"


class ChoiceModel(models.Model):
# Leave default unset so only the enum class can guide choices inference.
status = models.CharField(max_length=16, choices=Status)
nullable_status = models.CharField(max_length=16, choices=Status, null=True)
text = models.TextField(choices=Status)
nullable_text = models.TextField(choices=Status, null=True)
priority = models.IntegerField(choices=Priority)
nullable_priority = models.IntegerField(choices=Priority, null=True)
big_priority = models.BigIntegerField(choices=Priority)
nullable_big_priority = models.BigIntegerField(choices=Priority, null=True)
default_status = models.CharField(max_length=16, choices=Status, default=Status.DRAFT)
default_priority = models.IntegerField(choices=Priority, default=Priority.LOW)


def check_choice_field_types(instance: ChoiceModel) -> None:
assert_type(instance.status, str)
assert_type(instance.nullable_status, str | None)
assert_type(instance.text, str)
assert_type(instance.nullable_text, str | None)
assert_type(instance.priority, int)
assert_type(instance.nullable_priority, int | None)
assert_type(instance.big_priority, int)
assert_type(instance.nullable_big_priority, int | None)
assert_type(instance.default_status, str)
assert_type(instance.default_priority, int)


def reject_mismatched_choice_enums() -> None:
models.IntegerField(choices=Status) # pyright: ignore[reportArgumentType] # ty: ignore[invalid-argument-type]
models.CharField(max_length=16, choices=Priority) # pyright: ignore[reportArgumentType] # ty: ignore[invalid-argument-type]
24 changes: 24 additions & 0 deletions tests/trout/custom_fields_typing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from django.db import models
from typing_extensions import assert_type


class CustomCharField(models.CharField):
pass


class CustomIntegerField(models.IntegerField):
pass


class CustomFieldModel(models.Model):
nullable_char_default = CustomCharField(max_length=16, null=True, default=None)
nullable_char_db_default = CustomCharField(max_length=16, null=True, db_default=None)
nullable_integer_default = CustomIntegerField(null=True, default=None)
nullable_integer_db_default = CustomIntegerField(null=True, db_default=None)


def check_custom_field_types(instance: CustomFieldModel) -> None:
assert_type(instance.nullable_char_default, str | None)
assert_type(instance.nullable_char_db_default, str | None)
assert_type(instance.nullable_integer_default, int | None)
assert_type(instance.nullable_integer_db_default, int | None)
Loading
Loading