diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 78e832ee1..1a4a22ab2 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -17,6 +17,7 @@ Added - ``QuerySet.contains()`` method to check if an object exists in a queryset. - Added comprehensive EXPLAIN support for MySQL and PostgreSQL. - Built-in ``DomainNameValidator``, ``URLValidator``, and ``EmailValidator`` classes for common validation patterns. (#2162) +- Typed ``**kwargs`` on field constructors via PEP 692 (``Unpack[TypedDict]``), so IDEs and type checkers can autocomplete and validate common field arguments (``default``, ``null``, ``unique``, ``db_index``, ``description``, etc.). (#2168) Fixed ^^^^^ diff --git a/docs/conf.py b/docs/conf.py index dc3829e78..d58fdffaa 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -203,9 +203,7 @@ def get_version_info(): # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # -html_sidebars = { - "**": ["logo-text.html", "globaltoc.html", "localtoc.html", "searchbox.html"] -} +html_sidebars = {"**": ["logo-text.html", "globaltoc.html", "localtoc.html", "searchbox.html"]} # -- Options for HTMLHelp output --------------------------------------------- diff --git a/docs/sphinx_autodoc_typehints.py b/docs/sphinx_autodoc_typehints.py index f8c0dde56..b317c38cc 100644 --- a/docs/sphinx_autodoc_typehints.py +++ b/docs/sphinx_autodoc_typehints.py @@ -15,25 +15,33 @@ Protocol = None logger = logging.getLogger(__name__) -pydata_annotations = {'Any', 'AnyStr', 'Callable', 'ClassVar', 'NoReturn', 'Optional', 'Tuple', - 'Union'} +pydata_annotations = { + "Any", + "AnyStr", + "Callable", + "ClassVar", + "NoReturn", + "Optional", + "Tuple", + "Union", +} def format_annotation(annotation, fully_qualified=False): - if inspect.isclass(annotation) and annotation.__module__ == 'builtins': - if annotation.__qualname__ == 'NoneType': - return '``None``' + if inspect.isclass(annotation) and annotation.__module__ == "builtins": + if annotation.__qualname__ == "NoneType": + return "``None``" else: - return f':py:class:`{annotation.__qualname__}`' + return f":py:class:`{annotation.__qualname__}`" annotation_cls = annotation if inspect.isclass(annotation) else type(annotation) - if annotation_cls.__module__ == 'typing': - class_name = str(annotation).split('[')[0].split('.')[-1] + if annotation_cls.__module__ == "typing": + class_name = str(annotation).split("[")[0].split(".")[-1] params = None - module = 'typing' - extra = '' + module = "typing" + extra = "" - origin = getattr(annotation, '__origin__', None) + origin = getattr(annotation, "__origin__", None) if inspect.isclass(origin): annotation_cls = annotation.__origin__ try: @@ -44,13 +52,13 @@ def format_annotation(annotation, fully_qualified=False): pass # annotation_cls was either the "type" object or typing.Type if annotation is Any: - return ':py:data:`{}typing.Any`'.format("" if fully_qualified else "~") + return ":py:data:`{}typing.Any`".format("" if fully_qualified else "~") elif annotation is AnyStr: - return ':py:data:`{}typing.AnyStr`'.format("" if fully_qualified else "~") + return ":py:data:`{}typing.AnyStr`".format("" if fully_qualified else "~") elif isinstance(annotation, TypeVar): bound = annotation.__bound__ if bound: - if 'ForwardRef(' in str(bound): + if "ForwardRef(" in str(bound): try: bound = bound._evaluate(sys.modules[annotation.__module__].__dict__, None) except: @@ -59,28 +67,34 @@ def format_annotation(annotation, fully_qualified=False): except: bound = bound.__forward_arg__ return format_annotation(bound, fully_qualified) - return f'\\{annotation!r}' - elif (annotation is Union or getattr(annotation, '__origin__', None) is Union or - hasattr(annotation, '__union_params__')): - if hasattr(annotation, '__union_params__'): + return f"\\{annotation!r}" + elif ( + annotation is Union + or getattr(annotation, "__origin__", None) is Union + or hasattr(annotation, "__union_params__") + ): + if hasattr(annotation, "__union_params__"): params = annotation.__union_params__ - elif hasattr(annotation, '__args__'): + elif hasattr(annotation, "__args__"): params = annotation.__args__ - if params and len(params) == 2 and (hasattr(params[1], '__qualname__') and - params[1].__qualname__ == 'NoneType'): - class_name = 'Optional' + if ( + params + and len(params) == 2 + and (hasattr(params[1], "__qualname__") and params[1].__qualname__ == "NoneType") + ): + class_name = "Optional" params = (params[0],) - elif annotation_cls.__qualname__ == 'Tuple' and hasattr(annotation, '__tuple_params__'): + elif annotation_cls.__qualname__ == "Tuple" and hasattr(annotation, "__tuple_params__"): params = annotation.__tuple_params__ if annotation.__tuple_use_ellipsis__: params += (Ellipsis,) - elif annotation_cls.__qualname__ == 'Callable': + elif annotation_cls.__qualname__ == "Callable": arg_annotations = result_annotation = None - if hasattr(annotation, '__result__'): + if hasattr(annotation, "__result__"): arg_annotations = annotation.__args__ result_annotation = annotation.__result__ - elif getattr(annotation, '__args__', None): + elif getattr(annotation, "__args__", None): arg_annotations = annotation.__args__[:-1] result_annotation = annotation.__args__[-1] @@ -88,66 +102,74 @@ def format_annotation(annotation, fully_qualified=False): params = [Ellipsis, result_annotation] elif arg_annotations is not None: params = [ - '\\[{}]'.format( - ', '.join( - format_annotation(param, fully_qualified) - for param in arg_annotations)), - result_annotation + "\\[{}]".format( + ", ".join( + format_annotation(param, fully_qualified) for param in arg_annotations + ) + ), + result_annotation, ] - elif str(annotation).startswith('typing.ClassVar[') and hasattr(annotation, '__type__'): + elif str(annotation).startswith("typing.ClassVar[") and hasattr(annotation, "__type__"): # < py3.7 params = (annotation.__type__,) - elif hasattr(annotation, 'type_var'): + elif hasattr(annotation, "type_var"): # Type alias class_name = annotation.name params = (annotation.type_var,) - elif getattr(annotation, '__args__', None) is not None: + elif getattr(annotation, "__args__", None) is not None: params = annotation.__args__ - elif hasattr(annotation, '__parameters__'): + elif hasattr(annotation, "__parameters__"): params = annotation.__parameters__ if params: - extra = '\\[{}]'.format(', '.join( - format_annotation(param, fully_qualified) for param in params)) + extra = "\\[{}]".format( + ", ".join(format_annotation(param, fully_qualified) for param in params) + ) - return '{prefix}`{qualify}{module}.{name}`{extra}'.format( - prefix=':py:data:' if class_name in pydata_annotations else ':py:class:', + return "{prefix}`{qualify}{module}.{name}`{extra}".format( + prefix=":py:data:" if class_name in pydata_annotations else ":py:class:", qualify="" if fully_qualified else "~", module=module, name=class_name, - extra=extra + extra=extra, ) elif annotation is Ellipsis: - return '...' - elif (inspect.isfunction(annotation) and annotation.__module__ == 'typing' and - hasattr(annotation, '__name__') and hasattr(annotation, '__supertype__')): - return ':py:func:`{qualify}typing.NewType`\\(:py:data:`~{name}`, {extra})'.format( + return "..." + elif ( + inspect.isfunction(annotation) + and annotation.__module__ == "typing" + and hasattr(annotation, "__name__") + and hasattr(annotation, "__supertype__") + ): + return ":py:func:`{qualify}typing.NewType`\\(:py:data:`~{name}`, {extra})".format( qualify="" if fully_qualified else "~", name=annotation.__name__, extra=format_annotation(annotation.__supertype__, fully_qualified), ) - elif inspect.isclass(annotation) or inspect.isclass(getattr(annotation, '__origin__', None)): + elif inspect.isclass(annotation) or inspect.isclass(getattr(annotation, "__origin__", None)): if not inspect.isclass(annotation): annotation_cls = annotation.__origin__ - extra = '' + extra = "" try: mro = annotation_cls.mro() except TypeError: pass else: if Generic in mro or (Protocol and Protocol in mro): - params = (getattr(annotation, '__parameters__', None) or - getattr(annotation, '__args__', None)) + params = getattr(annotation, "__parameters__", None) or getattr( + annotation, "__args__", None + ) if params: - extra = '\\[{}]'.format(', '.join( - format_annotation(param, fully_qualified) for param in params)) + extra = "\\[{}]".format( + ", ".join(format_annotation(param, fully_qualified) for param in params) + ) - return ':py:class:`{qualify}{module}.{name}`{extra}'.format( + return ":py:class:`{qualify}{module}.{name}`{extra}".format( qualify="" if fully_qualified else "~", module=annotation.__module__, name=annotation_cls.__qualname__, - extra=extra + extra=extra, ) return str(annotation) @@ -157,31 +179,31 @@ def process_signature(app, what: str, name: str, obj, options, signature, return if not callable(obj): return - if what in ('class', 'exception'): - obj = getattr(obj, '__init__', getattr(obj, '__new__', None)) + if what in ("class", "exception"): + obj = getattr(obj, "__init__", getattr(obj, "__new__", None)) - if not getattr(obj, '__annotations__', None): + if not getattr(obj, "__annotations__", None): return obj = inspect.unwrap(obj) signature = Signature(obj) parameters = [ - param.replace(annotation=inspect.Parameter.empty) - for param in signature.parameters.values() + param.replace(annotation=inspect.Parameter.empty) for param in signature.parameters.values() ] - if '' in obj.__qualname__: + if "" in obj.__qualname__: logger.warning( 'Cannot treat a function defined as a local function: "%s" (use @functools.wraps)', - name) + name, + ) return if parameters: - if what in ('class', 'exception'): + if what in ("class", "exception"): del parameters[0] - elif what == 'method': + elif what == "method": outer = inspect.getmodule(obj) - for clsname in obj.__qualname__.split('.')[:-1]: + for clsname in obj.__qualname__.split(".")[:-1]: outer = getattr(outer, clsname) method_name = obj.__name__ @@ -189,18 +211,16 @@ def process_signature(app, what: str, name: str, obj, options, signature, return # If the method starts with double underscore (dunder) # Python applies mangling so we need to prepend the class name. # This doesn't happen if it always ends with double underscore. - class_name = obj.__qualname__.split('.')[-2] + class_name = obj.__qualname__.split(".")[-2] method_name = f"_{class_name}{method_name}" method_object = outer.__dict__[method_name] if outer else obj if not isinstance(method_object, (classmethod, staticmethod)): del parameters[0] - signature = signature.replace( - parameters=parameters, - return_annotation=inspect.Signature.empty) + signature = signature.replace(parameters=parameters, return_annotation=inspect.Signature.empty) - return stringify_signature(signature).replace('\\', '\\\\'), None + return stringify_signature(signature).replace("\\", "\\\\"), None def get_all_type_hints(obj, name): @@ -216,8 +236,9 @@ def get_all_type_hints(obj, name): try: rv = get_type_hints(obj, localns=type_globals.__dict__) except Exception as exc: - logger.warning('Cannot resolve forward reference in type annotations of "%s": %s', - name, exc) + logger.warning( + 'Cannot resolve forward reference in type annotations of "%s": %s', name, exc + ) rv = obj.__annotations__ if rv: @@ -238,8 +259,9 @@ def get_all_type_hints(obj, name): try: rv = get_type_hints(obj, localns=type_globals.__dict__) except: - logger.warning('Cannot resolve forward reference in type annotations of "%s": %s', - name, exc) + logger.warning( + 'Cannot resolve forward reference in type annotations of "%s": %s', name, exc + ) rv = obj.__annotations__ return rv @@ -248,14 +270,15 @@ def get_all_type_hints(obj, name): def backfill_type_hints(obj, name): import ast - parse_kwargs = {'type_comments': True} + parse_kwargs = {"type_comments": True} def _one_child(module): children = module.body # use the body to ignore type comments if len(children) != 1: logger.warning( - 'Did not get exactly one node from AST for "%s", got %s', name, len(children)) + 'Did not get exactly one node from AST for "%s", got %s', name, len(children) + ) return return children[0] @@ -278,14 +301,14 @@ def _one_child(module): return {} try: - comment_args_str, comment_returns = type_comment.split(' -> ') + comment_args_str, comment_returns = type_comment.split(" -> ") except ValueError: logger.warning('Unparsable type hint comment for "%s": Expected to contain ` -> `', name) return {} rv = {} if comment_returns: - rv['return'] = comment_returns + rv["return"] = comment_returns args = load_args(obj_ast) comment_args = split_type_comment_args(comment_args_str) @@ -317,7 +340,7 @@ def _one_child(module): def load_args(obj_ast): func_args = obj_ast.args args = [] - pos_only = getattr(func_args, 'posonlyargs', None) + pos_only = getattr(func_args, "posonlyargs", None) if pos_only: args.extend(pos_only) @@ -351,7 +374,7 @@ def add(val): add(comment[start_arg_at:at]) start_arg_at = at + 1 - add(comment[start_arg_at: at + 1]) + add(comment[start_arg_at : at + 1]) return result @@ -360,22 +383,23 @@ def process_docstring(app, what, name, obj, options, lines): obj = obj.fget if callable(obj): - if what in ('class', 'exception'): - obj = getattr(obj, '__init__') + if what in ("class", "exception"): + obj = getattr(obj, "__init__") obj = inspect.unwrap(obj) type_hints = get_all_type_hints(obj, name) for argname, annotation in type_hints.items(): - if argname == 'return': + if argname == "return": continue # this is handled separately later - if argname.endswith('_'): - argname = f'{argname[:-1]}\\_' + if argname.endswith("_"): + argname = f"{argname[:-1]}\\_" formatted_annotation = format_annotation( - annotation, fully_qualified=app.config.typehints_fully_qualified) + annotation, fully_qualified=app.config.typehints_fully_qualified + ) - searchfor = f':param {argname}:' + searchfor = f":param {argname}:" insert_index = None for i, line in enumerate(lines): @@ -388,31 +412,29 @@ def process_docstring(app, what, name, obj, options, lines): insert_index = len(lines) if insert_index is not None: - lines.insert( - insert_index, - f':type {argname}: {formatted_annotation}' - ) + lines.insert(insert_index, f":type {argname}: {formatted_annotation}") - if 'return' in type_hints and what not in ('class', 'exception'): + if "return" in type_hints and what not in ("class", "exception"): formatted_annotation = format_annotation( - type_hints['return'], fully_qualified=app.config.typehints_fully_qualified) + type_hints["return"], fully_qualified=app.config.typehints_fully_qualified + ) insert_index = len(lines) for i, line in enumerate(lines): - if line.startswith(':rtype:'): + if line.startswith(":rtype:"): insert_index = None break - elif line.startswith(':return:') or line.startswith(':returns:'): + elif line.startswith(":return:") or line.startswith(":returns:"): insert_index = i if insert_index is not None: if insert_index == len(lines): # Ensure that :rtype: doesn't get joined with a paragraph of text, which # prevents it being interpreted. - lines.append('') + lines.append("") insert_index += 1 - lines.insert(insert_index, f':rtype: {formatted_annotation}') + lines.insert(insert_index, f":rtype: {formatted_annotation}") def builder_ready(app): @@ -421,10 +443,10 @@ def builder_ready(app): def setup(app): - app.add_config_value('set_type_checking_flag', False, 'html') - app.add_config_value('always_document_param_types', False, 'html') - app.add_config_value('typehints_fully_qualified', False, 'env') - app.connect('builder-inited', builder_ready) - app.connect('autodoc-process-signature', process_signature) - app.connect('autodoc-process-docstring', process_docstring) + app.add_config_value("set_type_checking_flag", False, "html") + app.add_config_value("always_document_param_types", False, "html") + app.add_config_value("typehints_fully_qualified", False, "env") + app.connect("builder-inited", builder_ready) + app.connect("autodoc-process-signature", process_signature) + app.connect("autodoc-process-docstring", process_docstring) return dict(parallel_read_safe=True) diff --git a/tortoise/fields/base.py b/tortoise/fields/base.py index 81db786c0..1b7135f6e 100644 --- a/tortoise/fields/base.py +++ b/tortoise/fields/base.py @@ -4,7 +4,7 @@ import operator import sys import warnings -from collections.abc import Callable +from collections.abc import Awaitable, Callable from enum import Enum from functools import reduce from typing import TYPE_CHECKING, Any, Generic, TypeVar, overload @@ -12,6 +12,7 @@ from pypika_tortoise.terms import Term from tortoise.exceptions import ConfigurationError, ValidationError +from tortoise.fields.db_defaults import SqlDefault from tortoise.validators import Validator if TYPE_CHECKING: # pragma: nocoverage @@ -19,9 +20,13 @@ if sys.version_info >= (3, 11): from enum import StrEnum - from typing import Self + from typing import Self, TypedDict else: # pragma: no cover - from typing_extensions import Self + from collections.abc import Awaitable + + from typing_extensions import Self, TypedDict + # Under python 3.11, typing.TypedDict does not support multiple inheritance woth non-TypedDict + # So for Generic, used typing-extensions for TypedDict class StrEnum(str, Enum): __str__ = str.__str__ @@ -90,6 +95,85 @@ class OnDelete(StrEnum): NO_ACTION = OnDelete.NO_ACTION +class _FieldKwargsCommon(TypedDict, Generic[VALUE], total=False): + """:class:`Field` constructor arguments that are never declared as explicit parameters. + + Used with :data:`typing.Unpack` to give ``**kwargs`` explicit type hints. This is the + smallest set; fields that declare ``unique``/``db_index``/``primary_key`` explicitly + (e.g. ``TextField``) unpack this directly to avoid PEP 692 parameter-name collisions. + """ + + source_field: str | None + generated: bool + default: VALUE | Callable[..., VALUE | Awaitable[VALUE]] | None + db_default: VALUE | SqlDefault | _DB_DEFAULT_NOT_SET + description: str | None + model: Model | None + validators: list[Validator | Callable] + pk: bool # deprecated alias for primary_key + index: bool # deprecated alias for db_index + + +class _FieldKwargsNoPk(_FieldKwargsCommon[VALUE], total=False): + """Common arguments excluding ``primary_key`` and ``null``. + + For constructors that declare ``primary_key`` and ``null`` as explicit parameters + (e.g. ``IntField``). + """ + + unique: bool + db_index: bool | None + + +class FieldKwargs(_FieldKwargsNoPk[VALUE], total=False): + """Common arguments excluding ``null``. + + For constructors that declare only ``null`` as an explicit parameter (the majority). + """ + + primary_key: bool | None + + +class TextFieldKwargs(_FieldKwargsCommon[VALUE], total=False): + """Constructor arguments for :class:`TextField`. + + ``TextField`` doesn't declare ``null`` explicitly, so it includes it here. + """ + + null: bool + + +class JSONFieldKwargs(FieldKwargs[VALUE], total=False): + """Constructor arguments for :class:`JSONField`. + + ``JSONField`` declares neither ``null`` nor ``primary_key`` explicitly, and also accepts + a custom ``field_type`` (e.g. a Pydantic model class). + """ + + null: bool + field_type: type[Any] + + +class RelationalFieldKwargs(FieldKwargs[VALUE], total=False): + """Constructor arguments for :func:`ForeignKeyField` and :func:`OneToOneField`. + + Extends the common :class:`~tortoise.fields.base.FieldKwargs` with ``to_field``. + ``null`` is declared as an explicit parameter on those constructors, so it is omitted. + """ + + to_field: str | None + + +class ManyToManyFieldKwargs(_FieldKwargsCommon[VALUE], total=False): + """Constructor arguments for :func:`ManyToManyField`. + + ``unique`` is declared as an explicit parameter, so it is omitted here; the deprecated + ``create_unique_index`` alias is still accepted. + """ + + create_unique_index: bool # deprecated alias for unique + + class _FieldMeta(type): # TODO: Require functions to return field instances instead of this hack def __new__(mcs, name: str, bases: tuple[type, ...], attrs: dict) -> type: @@ -223,8 +307,8 @@ def __init__( generated: bool = False, primary_key: bool | None = None, null: bool = False, - default: Any = None, - db_default: Any = DB_DEFAULT_NOT_SET, + default: VALUE | Callable[..., VALUE | Awaitable[VALUE]] | None = None, + db_default: VALUE | SqlDefault | _DB_DEFAULT_NOT_SET = DB_DEFAULT_NOT_SET, unique: bool = False, db_index: bool | None = None, description: str | None = None, diff --git a/tortoise/fields/data.py b/tortoise/fields/data.py index 6109d0022..799e4729c 100644 --- a/tortoise/fields/data.py +++ b/tortoise/fields/data.py @@ -17,7 +17,13 @@ from tortoise import timezone from tortoise.exceptions import ConfigurationError, FieldError -from tortoise.fields.base import Field +from tortoise.fields.base import ( + Field, + FieldKwargs, + JSONFieldKwargs, + TextFieldKwargs, + _FieldKwargsNoPk, +) from tortoise.timezone import get_default_timezone, get_timezone, get_use_tz, localtime from tortoise.validators import MaxLengthValidator @@ -30,14 +36,23 @@ try: from pydantic import BaseModel as _PydanticBaseModel - from pydantic._internal._model_construction import ModelMetaclass as _PydanticModelMetaclass + from pydantic._internal._model_construction import ( + ModelMetaclass as _PydanticModelMetaclass, + ) except ImportError: _PydanticBaseModel = None # type: ignore[assignment,misc] _PydanticModelMetaclass = None # type: ignore[assignment,misc] if TYPE_CHECKING: # pragma: nocoverage + import sys + from tortoise.models import Model + if sys.version_info >= (3, 11): + from typing import Unpack + else: # pragma: no cover + from typing_extensions import Unpack + __all__ = ( "BigIntField", "BinaryField", @@ -107,7 +122,7 @@ def __init__( primary_key: bool | None = None, *, null: Literal[False] = False, - **kwargs: Any, + **kwargs: Unpack[_FieldKwargsNoPk[int]], ) -> None: ... @overload @@ -116,7 +131,7 @@ def __init__( primary_key: bool | None = None, *, null: Literal[True], - **kwargs: Any, + **kwargs: Unpack[_FieldKwargsNoPk[int]], ) -> None: ... def __init__(self, primary_key: bool | None = None, **kwargs: Any) -> None: @@ -222,12 +237,20 @@ class CharField(Field[T_STR]): @overload def __init__( - self: CharField[str], max_length: int, *, null: Literal[False] = False, **kwargs: Any + self: CharField[str], + max_length: int, + *, + null: Literal[False] = False, + **kwargs: Unpack[FieldKwargs[str]], ) -> None: ... @overload def __init__( - self: CharField[str | None], max_length: int, *, null: Literal[True], **kwargs: Any + self: CharField[str | None], + max_length: int, + *, + null: Literal[True], + **kwargs: Unpack[FieldKwargs[str]], ) -> None: ... def __init__(self, max_length: int, **kwargs: Any) -> None: @@ -269,7 +292,7 @@ def __init__( primary_key: bool | None = None, unique: bool = False, db_index: bool = False, - **kwargs: Any, + **kwargs: Unpack[TextFieldKwargs], ) -> None: if primary_key or kwargs.get("pk"): warnings.warn( @@ -315,12 +338,18 @@ class BooleanField(Field[T_BOOL]): @overload def __init__( - self: BooleanField[bool], *, null: Literal[False] = False, **kwargs: Any + self: BooleanField[bool], + *, + null: Literal[False] = False, + **kwargs: Unpack[FieldKwargs[bool]], ) -> None: ... @overload def __init__( - self: BooleanField[bool | None], *, null: Literal[True], **kwargs: Any + self: BooleanField[bool | None], + *, + null: Literal[True], + **kwargs: Unpack[FieldKwargs[bool]], ) -> None: ... def __init__(self, **kwargs: Any) -> None: @@ -357,7 +386,7 @@ def __init__( decimal_places: int, *, null: Literal[False] = False, - **kwargs: Any, + **kwargs: Unpack[FieldKwargs[Decimal]], ) -> None: ... @overload @@ -367,7 +396,7 @@ def __init__( decimal_places: int, *, null: Literal[True], - **kwargs: Any, + **kwargs: Unpack[FieldKwargs[Decimal]], ) -> None: ... def __init__(self, max_digits: int, decimal_places: int, **kwargs: Any) -> None: @@ -440,7 +469,7 @@ def __init__( auto_now_add: bool = False, *, null: Literal[False] = False, - **kwargs: Any, + **kwargs: Unpack[FieldKwargs[datetime.datetime]], ) -> None: ... @overload @@ -450,7 +479,7 @@ def __init__( auto_now_add: bool = False, *, null: Literal[True], - **kwargs: Any, + **kwargs: Unpack[FieldKwargs[datetime.datetime]], ) -> None: ... def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs: Any) -> None: @@ -530,12 +559,18 @@ class DateField(Field[T_DATE], datetime.date): @overload def __init__( - self: DateField[datetime.date], *, null: Literal[False] = False, **kwargs: Any + self: DateField[datetime.date], + *, + null: Literal[False] = False, + **kwargs: Unpack[FieldKwargs[datetime.date]], ) -> None: ... @overload def __init__( - self: DateField[datetime.date | None], *, null: Literal[True], **kwargs: Any + self: DateField[datetime.date | None], + *, + null: Literal[True], + **kwargs: Unpack[FieldKwargs[datetime.date]], ) -> None: ... def __init__(self, **kwargs: Any) -> None: @@ -574,7 +609,7 @@ def __init__( auto_now_add: bool = False, *, null: Literal[False] = False, - **kwargs: Any, + **kwargs: Unpack[FieldKwargs[datetime.time]], ) -> None: ... @overload @@ -584,7 +619,7 @@ def __init__( auto_now_add: bool = False, *, null: Literal[True], - **kwargs: Any, + **kwargs: Unpack[FieldKwargs[datetime.time]], ) -> None: ... def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs: Any) -> None: @@ -654,12 +689,18 @@ class TimeDeltaField(Field[T_TIMEDELTA]): @overload def __init__( - self: TimeDeltaField[datetime.timedelta], *, null: Literal[False] = False, **kwargs: Any + self: TimeDeltaField[datetime.timedelta], + *, + null: Literal[False] = False, + **kwargs: Unpack[FieldKwargs[datetime.timedelta]], ) -> None: ... @overload def __init__( - self: TimeDeltaField[datetime.timedelta | None], *, null: Literal[True], **kwargs: Any + self: TimeDeltaField[datetime.timedelta | None], + *, + null: Literal[True], + **kwargs: Unpack[FieldKwargs[datetime.timedelta]], ) -> None: ... def __init__(self, **kwargs: Any) -> None: @@ -692,11 +733,19 @@ class FloatField(Field[T_FLOAT], float): @overload def __init__( - self: FloatField[float], *, null: Literal[False] = False, **kwargs: Any + self: FloatField[float], + *, + null: Literal[False] = False, + **kwargs: Unpack[FieldKwargs[float]], ) -> None: ... @overload - def __init__(self: FloatField[float | None], *, null: Literal[True], **kwargs: Any) -> None: ... + def __init__( + self: FloatField[float | None], + *, + null: Literal[True], + **kwargs: Unpack[FieldKwargs[float]], + ) -> None: ... def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) @@ -748,7 +797,7 @@ def __init__( self, encoder: JsonDumpsFunc = JSON_DUMPS, decoder: JsonLoadsFunc = JSON_LOADS, - **kwargs: Any, + **kwargs: Unpack[JSONFieldKwargs[T]], ) -> None: super().__init__(**kwargs) self.encoder = encoder @@ -820,10 +869,20 @@ class _db_postgres: SQL_TYPE = "UUID" @overload - def __init__(self: UUIDField[UUID], *, null: Literal[False] = False, **kwargs: Any) -> None: ... + def __init__( + self: UUIDField[UUID], + *, + null: Literal[False] = False, + **kwargs: Unpack[FieldKwargs[UUID]], + ) -> None: ... @overload - def __init__(self: UUIDField[UUID | None], *, null: Literal[True], **kwargs: Any) -> None: ... + def __init__( + self: UUIDField[UUID | None], + *, + null: Literal[True], + **kwargs: Unpack[FieldKwargs[UUID]], + ) -> None: ... def __init__(self, **kwargs: Any) -> None: if (kwargs.get("primary_key") or kwargs.get("pk", False)) and "default" not in kwargs: @@ -852,12 +911,18 @@ class BinaryField(Field[T_BINARY], bytes): # type: ignore @overload def __init__( - self: BinaryField[bytes], *, null: Literal[False] = False, **kwargs: Any + self: BinaryField[bytes], + *, + null: Literal[False] = False, + **kwargs: Unpack[FieldKwargs[bytes]], ) -> None: ... @overload def __init__( - self: BinaryField[bytes | None], *, null: Literal[True], **kwargs: Any + self: BinaryField[bytes | None], + *, + null: Literal[True], + **kwargs: Unpack[FieldKwargs[bytes]], ) -> None: ... def __init__(self, **kwargs: Any) -> None: diff --git a/tortoise/fields/relational.py b/tortoise/fields/relational.py index 442707848..8523efa18 100644 --- a/tortoise/fields/relational.py +++ b/tortoise/fields/relational.py @@ -7,13 +7,27 @@ from pypika_tortoise.queries import Table from tortoise.exceptions import ConfigurationError, NoValuesFetched, OperationalError -from tortoise.fields.base import CASCADE, SET_NULL, Field, OnDelete +from tortoise.fields.base import ( + CASCADE, + SET_NULL, + Field, + ManyToManyFieldKwargs, + OnDelete, + RelationalFieldKwargs, +) if TYPE_CHECKING: # pragma: nocoverage + import sys + from tortoise.backends.base.client import BaseDBAsyncClient from tortoise.models import Model from tortoise.queryset import Q, QuerySet + if sys.version_info >= (3, 11): + from typing import Unpack + else: # pragma: no cover + from typing_extensions import Unpack + MODEL = TypeVar("MODEL", bound="Model") @@ -198,7 +212,10 @@ async def add(self, *instances: MODEL, using_db: BaseDBAsyncClient | None = None pks_f.append(pk_f) through_table = Table(self.field.through, schema=self.field.through_schema) backward_key, forward_key = self.field.backward_key, self.field.forward_key - backward_field, forward_field = through_table[backward_key], through_table[forward_key] + backward_field, forward_field = ( + through_table[backward_key], + through_table[forward_key], + ) select_query = ( db.query_class.from_(through_table).where(backward_field == pk_b).select(forward_key) ) @@ -441,7 +458,7 @@ def OneToOneField( db_constraint: bool = True, *, null: Literal[True], - **kwargs: Any, + **kwargs: Unpack[RelationalFieldKwargs], ) -> OneToOneNullableRelation[MODEL]: ... @@ -452,7 +469,7 @@ def OneToOneField( on_delete: OnDelete = CASCADE, db_constraint: bool = True, null: Literal[False] = False, - **kwargs: Any, + **kwargs: Unpack[RelationalFieldKwargs], ) -> OneToOneRelation[MODEL]: ... @@ -516,7 +533,7 @@ def ForeignKeyField( db_constraint: bool = True, *, null: Literal[True], - **kwargs: Any, + **kwargs: Unpack[RelationalFieldKwargs], ) -> ForeignKeyNullableRelation[MODEL]: ... @@ -527,7 +544,7 @@ def ForeignKeyField( on_delete: OnDelete = CASCADE, db_constraint: bool = True, null: Literal[False] = False, - **kwargs: Any, + **kwargs: Unpack[RelationalFieldKwargs], ) -> ForeignKeyRelation[MODEL]: ... @@ -592,7 +609,7 @@ def ManyToManyField( on_delete: OnDelete = CASCADE, db_constraint: bool = True, unique: bool = True, - **kwargs: Any, + **kwargs: Unpack[ManyToManyFieldKwargs], ) -> ManyToManyRelation[MODEL]: """ ManyToMany relation field.