MCPcopy
hub / github.com/ormar-orm/ormar / flatten_fields

Method flatten_fields

ormar/queryset/queryset.py:453–496  ·  view source on GitHub ↗

Render selected related models as their primary-key value on ``model_dump()`` instead of the default nested dict. Accepts the same input forms as :py:meth:`fields` / :py:meth:`exclude_fields` plus ``FieldAccessor`` / list of accessors. Missing relations are

(
        self,
        columns: Union[list, str, set, tuple, dict, FieldAccessor],
    )

Source from the content-addressed store, hash-verified

451 return self.rebuild_self(prefetch_related=related)
452
453 def flatten_fields(
454 self,
455 columns: Union[list, str, set, tuple, dict, FieldAccessor],
456 ) -> "QuerySet[T]":
457 """
458 Render selected related models as their primary-key value on
459 ``model_dump()`` instead of the default nested dict.
460
461 Accepts the same input forms as :py:meth:`fields` / :py:meth:`exclude_fields`
462 plus ``FieldAccessor`` / list of accessors. Missing relations are
463 auto-loaded: single-valued foreign keys go into ``select_related``,
464 many-to-many and reverse relations into ``prefetch_related``.
465
466 Chained calls merge. A flatten directive conflicts with any include or
467 exclude sub-field selection on the same relation (scalar output has no
468 place for children).
469
470 :param columns: relations to flatten on serialization
471 :type columns: Union[list, str, set, tuple, dict, FieldAccessor]
472 :return: new QuerySet with the flatten spec applied
473 :rtype: QuerySet[T]
474 """
475 normalized = extract_access_chains(columns)
476
477 excludable = ormar.ExcludableItems.from_excludable(self._excludable)
478 excludable.build(
479 items=normalized,
480 model_cls=self.model_cls, # type: ignore
481 slot="flatten",
482 )
483 excludable.validate_flatten_vs_excludable(
484 source_model=self.model_cls # type: ignore
485 )
486
487 select_to_add, prefetch_to_add = self._classify_flatten_paths(
488 excludable._flatten_paths
489 )
490 new_select = sorted(set(self._select_related) | select_to_add)
491 new_prefetch = sorted(set(self._prefetch_related) | prefetch_to_add)
492 return self.rebuild_self(
493 excludable=excludable,
494 select_related=new_select,
495 prefetch_related=new_prefetch,
496 )
497
498 def _classify_flatten_paths(
499 self, paths: Iterable[tuple[str, ...]]

Calls 6

rebuild_selfMethod · 0.95
extract_access_chainsFunction · 0.90
from_excludableMethod · 0.80
buildMethod · 0.80