Skip to content

fields.foreign_key

create_dummy_instance

1
create_dummy_instance(fk: Type["T"], pk: Any = None) -> "T"

Ormar never returns you a raw data. So if you have a related field that has a value populated it will construct you a Model instance out of it.

Creates a "fake" instance of passed Model from pk value. The instantiated Model has only pk value filled. To achieve this pk_only flag has to be passed as it skips the validation.

If the nested related Models are required they are set with -1 as pk value.

Arguments:

  • fk: class of the related Model to which instance should be constructed :type fk: Model class
  • pk: value of the primary_key column :type pk: Any

Returns:

Model instance populated with only pk :rtype: Model

create_dummy_model

1
create_dummy_model(base_model: Type["T"], pk_field: Union[BaseField, "ForeignKeyField", "ManyToManyField"]) -> Type["BaseModel"]

Used to construct a dummy pydantic model for type hints and pydantic validation. Populates only pk field and set it to desired type.

Arguments:

  • base_model: class of target dummy model :type base_model: Model class
  • pk_field: ormar Field to be set on pydantic Model :type pk_field: Union[BaseField, "ForeignKeyField", "ManyToManyField"]

Returns:

constructed dummy model :rtype: pydantic.BaseModel

populate_fk_params_based_on_to_model

1
populate_fk_params_based_on_to_model(to: Type["T"], nullable: bool, onupdate: str = None, ondelete: str = None) -> Tuple[Any, List, Any]

Based on target to model to which relation leads to populates the type of the pydantic field to use, ForeignKey constraint and type of the target column field.

Arguments:

  • to: target related ormar Model :type to: Model class
  • nullable: marks field as optional/ required :type nullable: bool
  • onupdate: parameter passed to sqlalchemy.ForeignKey. How to treat child rows on update of parent (the one where FK is defined) model. :type onupdate: str
  • ondelete: parameter passed to sqlalchemy.ForeignKey. How to treat child rows on delete of parent (the one where FK is defined) model. :type ondelete: str

Returns:

tuple with target pydantic type, list of fk constraints and target col type :rtype: Tuple[Any, List, Any]

validate_not_allowed_fields

1
validate_not_allowed_fields(kwargs: Dict) -> None

Verifies if not allowed parameters are set on relation models. Usually they are omitted later anyway but this way it's explicitly notify the user that it's not allowed/ supported.

Raises:

  • ModelDefinitionError: if any forbidden field is set

Arguments:

  • kwargs: dict of kwargs to verify passed to relation field :type kwargs: Dict

ForeignKeyConstraint Objects

1
2
@dataclass
class ForeignKeyConstraint()

Internal container to store ForeignKey definitions used later to produce sqlalchemy.ForeignKeys

ForeignKey

1
ForeignKey(to: "ToType", *, name: str = None, unique: bool = False, nullable: bool = True, related_name: str = None, virtual: bool = False, onupdate: str = None, ondelete: str = None, **kwargs: Any, ,) -> "T"

Despite a name it's a function that returns constructed ForeignKeyField. This function is actually used in model declaration (as ormar.ForeignKey(ToModel)).

Accepts number of relation setting parameters as well as all BaseField ones.

Arguments:

  • to: target related ormar Model :type to: Model class
  • name: name of the database field - later called alias :type name: str
  • unique: parameter passed to sqlalchemy.ForeignKey, unique flag :type unique: bool
  • nullable: marks field as optional/ required :type nullable: bool
  • related_name: name of reversed FK relation populated for you on to model :type related_name: str
  • virtual: marks if relation is virtual. It is for reversed FK and auto generated FK on through model in Many2Many relations. :type virtual: bool
  • onupdate: parameter passed to sqlalchemy.ForeignKey. How to treat child rows on update of parent (the one where FK is defined) model. :type onupdate: str
  • ondelete: parameter passed to sqlalchemy.ForeignKey. How to treat child rows on delete of parent (the one where FK is defined) model. :type ondelete: str
  • kwargs: all other args to be populated by BaseField :type kwargs: Any

Returns:

ormar ForeignKeyField with relation to selected model :rtype: ForeignKeyField

ForeignKeyField Objects

1
class ForeignKeyField(BaseField)

Actual class returned from ForeignKey function call and stored in model_fields.

1
 | get_source_related_name() -> str

Returns name to use for source relation name. For FK it's the same, differs for m2m fields. It's either set as related_name or by default it's owner model. get_name + 's'

Returns:

name of the related_name or default related name. :rtype: str

1
 | get_related_name() -> str

Returns name to use for reverse relation. It's either set as related_name or by default it's owner model. get_name + 's'

Returns:

name of the related_name or default related name. :rtype: str

default_target_field_name

1
 | default_target_field_name() -> str

Returns default target model name on through model.

Returns:

name of the field :rtype: str

default_source_field_name

1
 | default_source_field_name() -> str

Returns default target model name on through model.

Returns:

name of the field :rtype: str

evaluate_forward_ref

1
 | evaluate_forward_ref(globalns: Any, localns: Any) -> None

Evaluates the ForwardRef to actual Field based on global and local namespaces

Arguments:

  • globalns: global namespace :type globalns: Any
  • localns: local namespace :type localns: Any

Returns:

None :rtype: None

_extract_model_from_sequence

1
 | _extract_model_from_sequence(value: List, child: "Model", to_register: bool) -> List["Model"]

Takes a list of Models and registers them on parent. Registration is mutual, so children have also reference to parent.

Used in reverse FK relations.

Arguments:

  • value: list of Model :type value: List
  • child: child/ related Model :type child: Model
  • to_register: flag if the relation should be set in RelationshipManager :type to_register: bool

Returns:

list (if needed) registered Models :rtype: List["Model"]

_register_existing_model

1
 | _register_existing_model(value: "Model", child: "Model", to_register: bool) -> "Model"

Takes already created instance and registers it for parent. Registration is mutual, so children have also reference to parent.

Used in reverse FK relations and normal FK for single models.

Arguments:

  • value: already instantiated Model :type value: Model
  • child: child/ related Model :type child: Model
  • to_register: flag if the relation should be set in RelationshipManager :type to_register: bool

Returns:

(if needed) registered Model :rtype: Model

_construct_model_from_dict

1
 | _construct_model_from_dict(value: dict, child: "Model", to_register: bool) -> "Model"

Takes a dictionary, creates a instance and registers it for parent. If dictionary contains only one field and it's a pk it is a pk_only model. Registration is mutual, so children have also reference to parent.

Used in normal FK for dictionaries.

Arguments:

  • value: dictionary of a Model :type value: dict
  • child: child/ related Model :type child: Model
  • to_register: flag if the relation should be set in RelationshipManager :type to_register: bool

Returns:

(if needed) registered Model :rtype: Model

_construct_model_from_pk

1
 | _construct_model_from_pk(value: Any, child: "Model", to_register: bool) -> "Model"

Takes a pk value, creates a dummy instance and registers it for parent. Registration is mutual, so children have also reference to parent.

Used in normal FK for dictionaries.

Arguments:

  • value: value of a related pk / fk column :type value: Any
  • child: child/ related Model :type child: Model
  • to_register: flag if the relation should be set in RelationshipManager :type to_register: bool

Returns:

(if needed) registered Model :rtype: Model

register_relation

1
 | register_relation(model: "Model", child: "Model") -> None

Registers relation between parent and child in relation manager. Relation manager is kep on each model (different instance).

Used in Metaclass and sometimes some relations are missing (i.e. cloned Models in fastapi might miss one).

Arguments:

  • model: parent model (with relation definition) :type model: Model class
  • child: child model :type child: Model class

has_unresolved_forward_refs

1
 | has_unresolved_forward_refs() -> bool

Verifies if the filed has any ForwardRefs that require updating before the model can be used.

Returns:

result of the check :rtype: bool

expand_relationship

1
 | expand_relationship(value: Any, child: Union["Model", "NewBaseModel"], to_register: bool = True) -> Optional[Union["Model", List["Model"]]]

For relations the child model is first constructed (if needed), registered in relation and returned. For relation fields the value can be a pk value (Any type of field), dict (from Model) or actual instance/list of a "Model".

Selects the appropriate constructor based on a passed value.

Arguments:

  • value: a Model field value, returned untouched for non relation fields. :type value: Any
  • child: a child Model to register :type child: Union["Model", "NewBaseModel"]
  • to_register: flag if the relation should be set in RelationshipManager :type to_register: bool

Returns:

returns a Model or a list of Models :rtype: Optional[Union["Model", List["Model"]]]

get_relation_name

1
 | get_relation_name() -> str

Returns name of the relation, which can be a own name or through model names for m2m models

Returns:

result of the check :rtype: bool

get_source_model

1
 | get_source_model() -> Type["Model"]

Returns model from which the relation comes -> either owner or through model

Returns:

source model :rtype: Type["Model"]