django-stubs
django-stubs copied to clipboard
Add ORM protocols `Compilable` and `Resolvable`
Suggested by @charettes on a Django forum discussion regrading adding types to Django:
from __future__ import annotations
from typing import Protocol
from django.db.models import fields
from django.db.models.sql import compiler, query
class Compilable(Protocol):
"""
Object that can be compiled to a PEP 249 compliant tuple comprised of
a SQL string and its associated parameters sequence.
It can optionally have `as_vendor` methods defined to specialize the
compilation on different backends (e.g. `as_postgres`).
"""
def get_source_expressions(self) -> list[Compilable | None]: ...
def as_sql(
self, compiler: compiler.SQLCompiler, connection
) -> tuple[str, tuple]: ...
class Resolvable(Protocol):
"""
Object that can resolve any field and transform reference it has in
the context of a query and return an object ready to be compiled for
execution.
"""
output_field: fields.Field
def get_source_expressions(self) -> list[Resolvable | None]: ...
def resolve_expression(
self,
query: query.Query,
allow_joins: bool = True,
reuse: set[str] | None = None,
summarize: bool = False,
for_save: bool = False,
) -> Compilable: ...
I think we could try adding these in django-stubs and seeing how much simpler and more comprehensible they make things.
I think we could try adding these in django-stubs and seeing how much simpler and more comprehensible they make things.
This will require TYPING_CHECKING only imports, because django-stubs does not have runtime.
If you want them to be user accessible, then we can add them to django-stubs-ext
Making them user-accessible is probably the way forwards, so we can document them and explain how to use them. But it would need some experimentation.