Skip to content

models.newbasemodel

NewBaseModel Objects

1
class NewBaseModel(pydantic.BaseModel,  ModelTableProxy, metaclass=ModelMetaclass)

Main base class of ormar Model. Inherits from pydantic BaseModel and has all mixins combined in ModelTableProxy. Constructed with ModelMetaclass which in turn also inherits pydantic metaclass.

Abstracts away all internals and helper functions, so final Model class has only the logic concerned with database connection and data persistance.

__init__

1
 | __init__(*args: Any, **kwargs: Any) -> None

Initializer that creates a new ormar Model that is also pydantic Model at the same time.

Passed keyword arguments can be only field names and their corresponding values as those will be passed to pydantic validation that will complain if extra params are passed.

If relations are defined each relation is expanded and children models are also initialized and validated. Relation from both sides is registered so you can access related models from both sides.

Json fields are automatically loaded/dumped if needed.

Models marked as abstract=True in internal Meta class cannot be initialized.

Accepts also special pk_only flag that indicates that Model is constructed only with primary key value (so no other fields, it's a child model on other Model), that causes skipping the validation, that's the only case when the validation can be skipped.

Accepts also special excluded parameter that contains a set of fields that should be explicitly set to None, as otherwise pydantic will try to populate them with their default values if default is set.

Raises:

  • ModelError: if abstract model is initialized, model has ForwardRefs that has not been updated or unknown field is passed

Arguments:

  • args: ignored args :type args: Any
  • kwargs: keyword arguments - all fields values and some special params :type kwargs: Any

__setattr__

1
 | __setattr__(name: str, value: Any) -> None

Overwrites setattr in pydantic parent as otherwise descriptors are not called.

Arguments:

  • name: name of the attribute to set :type name: str
  • value: value of the attribute to set :type value: Any

Returns:

None :rtype: None

__getattr__

1
 | __getattr__(item: str) -> Any

Used only to silence mypy errors for Through models and reverse relations. Not used in real life as in practice calls are intercepted by RelationDescriptors

Arguments:

  • item: name of attribute :type item: str

Returns:

Any :rtype: Any

_internal_set

1
 | _internal_set(name: str, value: Any) -> None

Delegates call to pydantic.

Arguments:

  • name: name of param :type name: str
  • value: value to set :type value: Any

_verify_model_can_be_initialized

1
 | _verify_model_can_be_initialized() -> None

Raises exception if model is abstract or has ForwardRefs in relation fields.

Returns:

None :rtype: None

_process_kwargs

1
 | _process_kwargs(kwargs: Dict) -> Tuple[Dict, Dict]

Initializes nested models.

Removes property_fields

Checks if field is in the model fields or pydatnic fields.

Nullifies fields that should be excluded.

Extracts through models from kwargs into temporary dict.

Arguments:

  • kwargs: passed to init keyword arguments :type kwargs: Dict

Returns:

modified kwargs :rtype: Tuple[Dict, Dict]

_remove_extra_parameters_if_they_should_be_ignored

1
 | _remove_extra_parameters_if_they_should_be_ignored(kwargs: Dict, model_fields: Dict, pydantic_fields: Set) -> Dict

Removes the extra fields from kwargs if they should be ignored.

Arguments:

  • kwargs: passed arguments :type kwargs: Dict
  • model_fields: dictionary of model fields :type model_fields: Dict
  • pydantic_fields: set of pydantic fields names :type pydantic_fields: Set

Returns:

dict without extra fields :rtype: Dict

_initialize_internal_attributes

1
 | _initialize_internal_attributes() -> None

Initializes internal attributes during init() :rtype: None

__eq__

1
 | __eq__(other: object) -> bool

Compares other model to this model. when == is called.

Arguments:

  • other: other model to compare :type other: object

Returns:

result of comparison :rtype: bool

__same__

1
 | __same__(other: "NewBaseModel") -> bool

Used by eq, compares other model to this model. Compares: * _orm_ids, * primary key values if it's set * dictionary of own fields (excluding relations)

Arguments:

  • other: model to compare to :type other: NewBaseModel

Returns:

result of comparison :rtype: bool

get_name

1
2
 | @classmethod
 | get_name(cls, lower: bool = True) -> str

Returns name of the Model class, by default lowercase.

Arguments:

  • lower: flag if name should be set to lowercase :type lower: bool

Returns:

name of the model :rtype: str

pk_column

1
2
 | @property
 | pk_column() -> sqlalchemy.Column

Retrieves primary key sqlalchemy column from models Meta.table. Each model has to have primary key. Only one primary key column is allowed.

Returns:

primary key sqlalchemy column :rtype: sqlalchemy.Column

saved

1
2
 | @property
 | saved() -> bool

Saved status of the model. Changed by setattr and loading from db

signals

1
2
 | @property
 | signals() -> "SignalEmitter"

Exposes signals from model Meta

pk_type

1
2
 | @classmethod
 | pk_type(cls) -> Any

Shortcut to models primary key field type

db_backend_name

1
2
 | @classmethod
 | db_backend_name(cls) -> str

Shortcut to database dialect, cause some dialect require different treatment

remove

1
 | remove(parent: "Model", name: str) -> None

Removes child from relation with given name in RelationshipManager

set_save_status

1
 | set_save_status(status: bool) -> None

Sets value of the save status

get_properties

1
2
 | @classmethod
 | get_properties(cls, include: Union[Set, Dict, None], exclude: Union[Set, Dict, None]) -> Set[str]

Returns a set of names of functions/fields decorated with @property_field decorator.

They are added to dictionary when called directly and therefore also are present in fastapi responses.

Arguments:

  • include: fields to include :type include: Union[Set, Dict, None]
  • exclude: fields to exclude :type exclude: Union[Set, Dict, None]

Returns:

set of property fields names :rtype: Set[str]

update_forward_refs

1
2
 | @classmethod
 | update_forward_refs(cls, **localns: Any) -> None

Processes fields that are ForwardRef and need to be evaluated into actual models.

Expands relationships, register relation in alias manager and substitutes sqlalchemy columns with new ones with proper column type (null before).

Populates Meta table of the Model which is left empty before.

Sets self_reference flag on models that links to themselves.

Calls the pydantic method to evaluate pydantic fields.

Arguments:

  • localns: local namespace :type localns: Any

Returns:

None :rtype: None

_get_not_excluded_fields

1
2
 | @staticmethod
 | _get_not_excluded_fields(fields: Union[List, Set], include: Optional[Dict], exclude: Optional[Dict]) -> List

Returns related field names applying on them include and exclude set.

Arguments:

  • include: fields to include :type include: Union[Set, Dict, None]
  • exclude: fields to exclude :type exclude: Union[Set, Dict, None]

Returns:

:rtype: List of fields with relations that is not excluded

_extract_nested_models_from_list

1
2
 | @staticmethod
 | _extract_nested_models_from_list(relation_map: Dict, models: MutableSequence, include: Union[Set, Dict, None], exclude: Union[Set, Dict, None], exclude_primary_keys: bool, exclude_through_models: bool) -> List

Converts list of models into list of dictionaries.

Arguments:

  • models: List of models :type models: List
  • include: fields to include :type include: Union[Set, Dict, None]
  • exclude: fields to exclude :type exclude: Union[Set, Dict, None]

Returns:

list of models converted to dictionaries :rtype: List[Dict]

_skip_ellipsis

1
2
 | @classmethod
 | _skip_ellipsis(cls, items: Union[Set, Dict, None], key: str, default_return: Any = None) -> Union[Set, Dict, None]

Helper to traverse the include/exclude dictionaries. In dict() Ellipsis should be skipped as it indicates all fields required and not the actual set/dict with fields names.

Arguments:

  • items: current include/exclude value :type items: Union[Set, Dict, None]
  • key: key for nested relations to check :type key: str

Returns:

nested value of the items :rtype: Union[Set, Dict, None]

_convert_all

1
2
 | @staticmethod
 | _convert_all(items: Union[Set, Dict, None]) -> Union[Set, Dict, None]

Helper to convert all pydantic special index to ormar which does not support index based exclusions.

Arguments:

  • items: current include/exclude value :type items: Union[Set, Dict, None]

_extract_nested_models

1
 | _extract_nested_models(relation_map: Dict, dict_instance: Dict, include: Optional[Dict], exclude: Optional[Dict], exclude_primary_keys: bool, exclude_through_models: bool) -> Dict

Traverse nested models and converts them into dictionaries. Calls itself recursively if needed.

Arguments:

  • nested: flag if current instance is nested :type nested: bool
  • dict_instance: current instance dict :type dict_instance: Dict
  • include: fields to include :type include: Optional[Dict]
  • exclude: fields to exclude :type exclude: Optional[Dict]

Returns:

current model dict with child models converted to dictionaries :rtype: Dict

dict

1
 | dict(*, include: Union[Set, Dict] = None, exclude: Union[Set, Dict] = None, by_alias: bool = False, skip_defaults: bool = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_primary_keys: bool = False, exclude_through_models: bool = False, relation_map: Dict = None) -> "DictStrAny"

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Nested models are also parsed to dictionaries.

Additionally fields decorated with @property_field are also added.

Arguments:

  • exclude_through_models: flag to exclude through models from dict :type exclude_through_models: bool
  • exclude_primary_keys: flag to exclude primary keys from dict :type exclude_primary_keys: bool
  • include: fields to include :type include: Union[Set, Dict, None]
  • exclude: fields to exclude :type exclude: Union[Set, Dict, None]
  • by_alias: flag to get values by alias - passed to pydantic :type by_alias: bool
  • skip_defaults: flag to not set values - passed to pydantic :type skip_defaults: bool
  • exclude_unset: flag to exclude not set values - passed to pydantic :type exclude_unset: bool
  • exclude_defaults: flag to exclude default values - passed to pydantic :type exclude_defaults: bool
  • exclude_none: flag to exclude None values - passed to pydantic :type exclude_none: bool
  • relation_map: map of the relations to follow to avoid circural deps :type relation_map: Dict

Returns:

:rtype:

json

1
 | json(*, include: Union[Set, Dict] = None, exclude: Union[Set, Dict] = None, by_alias: bool = False, skip_defaults: bool = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, exclude_primary_keys: bool = False, exclude_through_models: bool = False, **dumps_kwargs: Any, ,) -> str

Generate a JSON representation of the model, include and exclude arguments as per dict().

encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().

update_from_dict

1
 | update_from_dict(value_dict: Dict) -> "NewBaseModel"

Updates self with values of fields passed in the dictionary.

Arguments:

  • value_dict: dictionary of fields names and values :type value_dict: Dict

Returns:

self :rtype: NewBaseModel

_convert_to_bytes

1
 | _convert_to_bytes(column_name: str, value: Any) -> Union[str, Dict]

Converts value to bytes from string

Arguments:

  • column_name: name of the field :type column_name: str
  • value: value fo the field :type value: Any

Returns:

converted value if needed, else original value :rtype: Any

_convert_bytes_to_str

1
 | _convert_bytes_to_str(column_name: str, value: Any) -> Union[str, Dict]

Converts value to str from bytes for represent_as_base64_str columns.

Arguments:

  • column_name: name of the field :type column_name: str
  • value: value fo the field :type value: Any

Returns:

converted value if needed, else original value :rtype: Any

_convert_json

1
 | _convert_json(column_name: str, value: Any) -> Union[str, Dict]

Converts value to/from json if needed (for Json columns).

Arguments:

  • column_name: name of the field :type column_name: str
  • value: value fo the field :type value: Any

Returns:

converted value if needed, else original value :rtype: Any

_extract_own_model_fields

1
 | _extract_own_model_fields() -> Dict

Returns a dictionary with field names and values for fields that are not relations fields (ForeignKey, ManyToMany etc.)

Returns:

dictionary of fields names and values. :rtype: Dict

_extract_model_db_fields

1
 | _extract_model_db_fields() -> Dict

Returns a dictionary with field names and values for fields that are stored in current model's table.

That includes own non-relational fields ang foreign key fields.

Returns:

dictionary of fields names and values. :rtype: Dict

get_relation_model_id

1
 | get_relation_model_id(target_field: "BaseField") -> Optional[int]

Returns an id of the relation side model to use in prefetch query.

Arguments:

  • target_field: field with relation definition :type target_field: "BaseField"

Returns:

value of pk if set :rtype: Optional[int]