1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
|
import builtins
import copy
import dataclasses
import functools
import inspect
import sys
import types
from collections.abc import Callable, Collection, Sequence
from typing import (
Generic,
Literal,
TypeVar,
cast,
)
import strawberry
from django.core.exceptions import FieldDoesNotExist
from django.db.models import ForeignKey
from django.db.models.base import Model
from django.db.models.fields.reverse_related import ManyToManyRel, ManyToOneRel
from strawberry import UNSET, relay
from strawberry.annotation import StrawberryAnnotation
from strawberry.exceptions import (
MissingFieldAnnotationError,
)
from strawberry.types import get_object_definition
from strawberry.types.base import WithStrawberryObjectDefinition
from strawberry.types.cast import get_strawberry_type_cast
from strawberry.types.field import StrawberryField
from strawberry.types.private import is_private
from strawberry.utils.deprecations import DeprecatedDescriptor
from typing_extensions import Self, dataclass_transform, get_annotations
from strawberry_django.optimizer import OptimizerStore
from strawberry_django.relay import (
resolve_model_id,
resolve_model_id_attr,
resolve_model_node,
resolve_model_nodes,
)
from strawberry_django.resolvers import django_resolver
from strawberry_django.utils.typing import (
AnnotateType,
PrefetchType,
TypeOrMapping,
TypeOrSequence,
WithStrawberryDjangoObjectDefinition,
get_strawberry_annotations,
is_auto,
)
from .descriptors import ModelProperty
from .fields.field import StrawberryDjangoField
from .fields.field import field as _field
from .fields.types import get_model_field, resolve_model_field_name
from .settings import strawberry_django_settings as django_settings
__all__ = [
"StrawberryDjangoDefinition",
"input",
"interface",
"partial",
"type",
]
_T = TypeVar("_T", bound=type)
_O = TypeVar("_O", bound=type[WithStrawberryObjectDefinition])
_M = TypeVar("_M", bound=Model)
def _process_type(
cls: _T,
model: type[Model],
*,
field_cls: type[StrawberryDjangoField] = StrawberryDjangoField,
filters: type | None = None,
order: type | None = None,
ordering: type | None = None,
pagination: bool = False,
partial: bool = False,
is_filter: Literal["lookups"] | bool = False,
only: TypeOrSequence[str] | None = None,
select_related: TypeOrSequence[str] | None = None,
prefetch_related: TypeOrSequence[PrefetchType] | None = None,
annotate: TypeOrMapping[AnnotateType] | None = None,
disable_optimization: bool = False,
fields: list[str] | Literal["__all__"] | None = None,
exclude: list[str] | None = None,
**kwargs,
) -> _T:
is_input = kwargs.get("is_input", False)
if fields == "__all__":
model_fields = list(model._meta.fields)
elif isinstance(fields, Collection):
model_fields = [f for f in model._meta.fields if f.name in fields]
elif isinstance(exclude, Collection) and len(exclude) > 0:
model_fields = [f for f in model._meta.fields if f.name not in exclude]
else:
model_fields = []
# If MAP_AUTO_ID_AS_GLOBAL_ID is True, we can no longer set the id
# from fields or it will override the GlobalID and return the default
# django id instead in the query-result. This adjustment however still
# does not fix if the id was set to auto manually on the ModelType.
if django_settings().get("MAP_AUTO_ID_AS_GLOBAL_ID", False):
model_fields = [f for f in model_fields if f.name != "id"]
existing_annotations = get_strawberry_annotations(cls)
cls_annotations = get_annotations(cls)
cls.__annotations__ = cls_annotations
for f in model_fields:
if existing_annotations.get(f.name):
continue
cls_annotations[f.name] = strawberry.auto
if is_filter:
cls_annotations.update(
{
"AND": existing_annotations.get("AND").annotation # type: ignore
if existing_annotations.get("AND")
else Self | None,
"OR": existing_annotations.get("OR").annotation # type: ignore
if existing_annotations.get("OR")
else Self | None,
"NOT": existing_annotations.get("NOT").annotation # type: ignore
if existing_annotations.get("NOT")
else Self | None,
"DISTINCT": existing_annotations.get("DISTINCT").annotation # type: ignore
if existing_annotations.get("DISTINCT")
else bool | None,
},
)
django_type = StrawberryDjangoDefinition(
origin=cast("builtins.type[WithStrawberryObjectDefinition]", cls),
model=model,
field_cls=field_cls,
is_partial=partial,
is_input=is_input,
is_filter=is_filter,
filters=filters,
order=order,
ordering=ordering,
pagination=pagination,
disable_optimization=disable_optimization,
store=OptimizerStore.with_hints(
only=only,
select_related=select_related,
prefetch_related=prefetch_related,
annotate=annotate,
),
)
auto_fields: set[str] = set()
for field_name, field_annotation in get_strawberry_annotations(cls).items():
annotation = field_annotation.annotation
if is_private(annotation):
continue
if is_auto(annotation):
auto_fields.add(field_name)
# FIXME: For input types it is important to set the default value to UNSET
# Is there a better way of doing this?
if is_input:
# First check if the field is defined in the class. If it is,
# then we just need to set its default value to UNSET in case
# it is MISSING
if field_name in cls.__dict__:
field = cls.__dict__[field_name]
if (
isinstance(field, dataclasses.Field)
and field.default is dataclasses.MISSING
):
field.default = UNSET
if isinstance(field, StrawberryField):
field.default_value = UNSET
continue
if not hasattr(cls, field_name):
base_field = getattr(cls, "__dataclass_fields__", {}).get(field_name)
if base_field is not None and isinstance(base_field, StrawberryField):
new_field = copy.copy(base_field)
else:
new_field = _field(default=UNSET)
cls_annotations[field_name] = field_annotation.raw_annotation
new_field.default = UNSET
if isinstance(base_field, StrawberryField):
new_field.default_value = UNSET
setattr(cls, field_name, new_field)
# Make sure model is also considered a "virtual subclass" of cls
if "is_type_of" not in cls.__dict__:
def is_type_of(obj, info):
if (type_cast := get_strawberry_type_cast(obj)) is not None:
return type_cast is cls
return isinstance(obj, (cls, model))
cls.is_type_of = is_type_of
# Default querying methods for relay
if issubclass(cls, relay.Node):
for attr, func in [
("resolve_id", resolve_model_id),
("resolve_id_attr", resolve_model_id_attr),
("resolve_node", resolve_model_node),
("resolve_nodes", resolve_model_nodes),
]:
existing_resolver = getattr(cls, attr, None)
if (
existing_resolver is None
or existing_resolver.__func__ is getattr(relay.Node, attr).__func__
):
setattr(cls, attr, types.MethodType(django_resolver(func), cls)) # type: ignore
# Adjust types that inherit from other types/interfaces that implement Node
# to make sure they pass themselves as the node type
meth = getattr(cls, attr)
if isinstance(meth, types.MethodType) and meth.__self__ is not cls:
setattr(
cls,
attr,
types.MethodType(cast("classmethod", meth).__func__, cls),
)
settings = django_settings()
if (
kwargs.get("description") is None
and model.__doc__
and settings["TYPE_DESCRIPTION_FROM_MODEL_DOCSTRING"]
):
kwargs["description"] = inspect.cleandoc(model.__doc__)
strawberry.type(cls, **kwargs)
# update annotations and fields
type_def = get_object_definition(cls, strict=True)
description_from_doc = settings["FIELD_DESCRIPTION_FROM_HELP_TEXT"]
new_fields: list[StrawberryField] = []
for f in type_def.fields:
django_name: str | None = (
getattr(f, "django_name", None) or f.python_name or f.name
)
assert django_name is not None
description: str | None = getattr(f, "description", None)
type_annotation: StrawberryAnnotation | None = getattr(
f,
"type_annotation",
None,
)
# We need to reset the `__eval_cache__` to make sure inherited types
# will be forced to reevaluate the annotation on strawberry 0.192.2+
if type_annotation is not None and hasattr(
type_annotation,
"__resolve_cache__",
):
type_annotation.__resolve_cache__ = None
if f.name in auto_fields:
f_is_auto = True
# Force the field to be auto again for it to be re-evaluated
if type_annotation:
type_annotation.annotation = strawberry.auto
else:
f_is_auto = type_annotation is not None and is_auto(
type_annotation.annotation,
)
try:
model_attr = get_model_field(django_type.model, django_name)
except FieldDoesNotExist as e:
model_attr = getattr(django_type.model, django_name, None)
is_relation = False
if model_attr is not None and isinstance(model_attr, ModelProperty):
if type_annotation is None or f_is_auto:
type_annotation = StrawberryAnnotation(
model_attr.type_annotation,
namespace=sys.modules[model_attr.func.__module__].__dict__,
)
if description is None and description_from_doc:
description = model_attr.description
f_is_auto = False
elif model_attr is not None and isinstance(
model_attr,
(property, functools.cached_property),
):
func = (
model_attr.fget
if isinstance(model_attr, property)
else model_attr.func
)
if type_annotation is None or f_is_auto:
return_type = get_annotations(func).get("return")
if return_type is None:
raise MissingFieldAnnotationError(
django_name,
type_def.origin,
) from e
type_annotation = StrawberryAnnotation(
return_type,
namespace=sys.modules[func.__module__].__dict__,
)
if description is None and func.__doc__ and description_from_doc:
description = inspect.cleandoc(func.__doc__)
f_is_auto = False
if type_annotation is None or f_is_auto:
raise
else:
is_relation = model_attr.is_relation
django_name = getattr(f, "django_name", None) or resolve_model_field_name(
model_attr,
is_input=django_type.is_input,
is_filter=bool(django_type.is_filter),
is_fk_id=(
f.python_name.endswith("_id") and isinstance(model_attr, ForeignKey)
),
)
if description is None and description_from_doc:
try:
from django.contrib.contenttypes.fields import (
GenericForeignKey,
GenericRel,
)
except (ImportError, RuntimeError): # pragma: no cover
GenericForeignKey = None # noqa: N806
GenericRel = None # noqa: N806
if (
GenericForeignKey is not None
and GenericRel is not None
and isinstance(model_attr, (GenericRel, GenericForeignKey))
):
f_description = None
elif isinstance(model_attr, (ManyToOneRel, ManyToManyRel)):
f_description = model_attr.field.help_text
else:
f_description = getattr(model_attr, "help_text", None)
if f_description:
description = str(f_description)
if isinstance(f, StrawberryDjangoField) and not f.origin_django_type:
# If the field is a StrawberryDjangoField and it is the first time
# seeing it, just update its annotations/description/etc
f.type_annotation = type_annotation
f.description = description
elif isinstance(f, StrawberryDjangoField):
f = copy.copy(f) # noqa: PLW2901
elif (
not isinstance(f, StrawberryDjangoField)
and getattr(f, "base_resolver", None) is not None
):
# If this is not a StrawberryDjangoField, but has a base_resolver, no need
# avoid forcing it to be a StrawberryDjangoField
new_fields.append(f)
continue
else:
f = field_cls( # noqa: PLW2901
django_name=django_name,
description=description,
type_annotation=type_annotation,
python_name=f.python_name,
graphql_name=getattr(f, "graphql_name", None),
origin=getattr(f, "origin", None),
is_subscription=getattr(f, "is_subscription", False),
base_resolver=getattr(f, "base_resolver", None),
permission_classes=getattr(f, "permission_classes", ()),
default=getattr(f, "default", dataclasses.MISSING),
default_factory=getattr(f, "default_factory", dataclasses.MISSING),
metadata=getattr(f, "metadata", None),
deprecation_reason=getattr(f, "deprecation_reason", None),
directives=getattr(f, "directives", ()),
pagination=getattr(f, "pagination", UNSET),
filters=getattr(f, "filters", UNSET),
order=getattr(f, "order", UNSET),
extensions=getattr(f, "extensions", ()),
)
f.django_name = django_name
f.is_relation = is_relation
f.origin_django_type = django_type
new_fields.append(f)
if f.base_resolver and f.python_name:
setattr(cls, f.python_name, f)
type_def.fields = new_fields
cls.__strawberry_django_definition__ = django_type # type: ignore
# TODO: remove when deprecating _type_definition
DeprecatedDescriptor(
"_django_type is deprecated, use __strawberry_django_definition__ instead",
cast(
"WithStrawberryDjangoObjectDefinition",
cls,
).__strawberry_django_definition__,
"_django_type",
).inject(cls)
return cast("_T", cls)
@dataclasses.dataclass
class StrawberryDjangoDefinition(Generic[_O, _M]):
origin: _O
model: type[_M]
store: OptimizerStore
is_input: bool = False
is_partial: bool = False
is_filter: Literal["lookups"] | bool = False
filters: type | None = None
order: type | None = None
ordering: type | None = None
pagination: bool = False
field_cls: type[StrawberryDjangoField] = StrawberryDjangoField
disable_optimization: bool = False
@dataclass_transform(
kw_only_default=True,
order_default=True,
field_specifiers=(
StrawberryField,
_field,
),
)
def type( # noqa: A001
model: type[Model],
*,
name: str | None = None,
field_cls: type[StrawberryDjangoField] = StrawberryDjangoField,
is_input: bool = False,
is_interface: bool = False,
is_filter: Literal["lookups"] | bool = False,
description: str | None = None,
directives: Sequence[object] | None = (),
extend: bool = False,
filters: type | None = None,
order: type | None = None,
ordering: type | None = None,
pagination: bool = False,
only: TypeOrSequence[str] | None = None,
select_related: TypeOrSequence[str] | None = None,
prefetch_related: TypeOrSequence[PrefetchType] | None = None,
annotate: TypeOrMapping[AnnotateType] | None = None,
disable_optimization: bool = False,
fields: list[str] | Literal["__all__"] | None = None,
exclude: list[str] | None = None,
) -> Callable[[_T], _T]:
"""Annotates a class as a Django GraphQL type.
Examples
--------
It can be used like this:
>>> @strawberry_django.type(SomeModel)
... class X:
... some_field: strawberry.auto
... otherfield: str = strawberry_django.field()
"""
def wrapper(cls: _T) -> _T:
return _process_type(
cls,
model,
name=name,
field_cls=field_cls,
is_input=is_input,
is_filter=is_filter,
is_interface=is_interface,
description=description,
directives=directives,
extend=extend,
filters=filters,
pagination=pagination,
order=order,
ordering=ordering,
only=only,
select_related=select_related,
prefetch_related=prefetch_related,
annotate=annotate,
disable_optimization=disable_optimization,
fields=fields,
exclude=exclude,
)
return wrapper
@dataclass_transform(
kw_only_default=True,
order_default=True,
field_specifiers=(
StrawberryField,
_field,
),
)
def interface(
model: builtins.type[Model],
*,
name: str | None = None,
field_cls: builtins.type[StrawberryDjangoField] = StrawberryDjangoField,
description: str | None = None,
directives: Sequence[object] | None = (),
disable_optimization: bool = False,
) -> Callable[[_T], _T]:
"""Annotates a class as a Django GraphQL interface.
Examples
--------
It can be used like this:
>>> @strawberry_django.interface(SomeModel)
... class X:
... some_field: strawberry.auto
... otherfield: str = strawberry_django.field()
"""
def wrapper(cls: _T) -> _T:
return _process_type(
cls,
model,
name=name,
field_cls=field_cls,
is_interface=True,
description=description,
directives=directives,
disable_optimization=disable_optimization,
)
return wrapper
@dataclass_transform(
kw_only_default=True,
order_default=True,
field_specifiers=(
StrawberryField,
_field,
),
)
def input( # noqa: A001
model: builtins.type[Model],
*,
name: str | None = None,
field_cls: builtins.type[StrawberryDjangoField] = StrawberryDjangoField,
description: str | None = None,
directives: Sequence[object] | None = (),
is_filter: Literal["lookups"] | bool = False,
partial: bool = False,
fields: list[str] | Literal["__all__"] | None = None,
exclude: list[str] | None = None,
) -> Callable[[_T], _T]:
"""Annotates a class as a Django GraphQL input.
Examples
--------
It can be used like this:
>>> @strawberry_django.input(SomeModel)
... class X:
... some_field: strawberry.auto
... otherfield: str = strawberry_django.field()
"""
def wrapper(cls: _T) -> _T:
return _process_type(
cls,
model,
name=name,
field_cls=field_cls,
is_input=True,
is_filter=is_filter,
description=description,
directives=directives,
partial=partial,
fields=fields,
exclude=exclude,
)
return wrapper
@dataclass_transform(
kw_only_default=True,
order_default=True,
field_specifiers=(
StrawberryField,
_field,
),
)
def partial(
model: builtins.type[Model],
*,
name: str | None = None,
field_cls: builtins.type[StrawberryDjangoField] = StrawberryDjangoField,
description: str | None = None,
directives: Sequence[object] | None = (),
fields: list[str] | Literal["__all__"] | None = None,
exclude: list[str] | None = None,
) -> Callable[[_T], _T]:
"""Annotates a class as a Django GraphQL partial.
Examples
--------
It can be used like this:
>>> @strawberry_django.partial(SomeModel)
... class X:
... some_field: strawberry.auto
... otherfield: str = strawberry_django.field()
"""
def wrapper(cls: _T) -> _T:
return _process_type(
cls,
model,
name=name,
field_cls=field_cls,
is_input=True,
description=description,
directives=directives,
partial=True,
fields=fields,
exclude=exclude,
)
return wrapper
|