Skip to content

odmantic.model

odmantic.model._BaseODMModel private

Base class for Model and EmbeddedModel.

Warning

This internal class should never be instanciated directly.

doc(self, include=None)

Generate a document representation of the instance (as a dictionary).

Parameters:

Name Type Description Default
include Optional[AbstractSetIntStr]

field that should be included; if None, all the field will be included

None

Returns:

Type Description
Dict[str, Any]

the document associated to the instance

Source code in odmantic/model.py
def doc(self, include: Optional["AbstractSetIntStr"] = None) -> Dict[str, Any]:
    """Generate a document representation of the instance (as a dictionary).

    Args:
        include: field that should be included; if None, all the field will be
            included

    Returns:
        the document associated to the instance
    """
    raw_doc = self.dict()
    doc: Dict[str, Any] = {}
    for field_name, field in self.__odm_fields__.items():
        if include is not None and field_name not in include:
            continue
        if isinstance(field, ODMReference):
            doc[field.key_name] = raw_doc[field_name]["id"]
        else:
            if field_name in self.__bson_serialized_fields__:
                doc[field.key_name] = self.__fields__[field_name].type_.__bson__(
                    raw_doc[field_name]
                )
            else:
                doc[field.key_name] = raw_doc[field_name]
    return doc

parse_doc(raw_doc) classmethod

Parse a BSON document into an instance of the Model

Parameters:

Name Type Description Default
raw_doc Dict

document to parse (as Dict)

required

Exceptions:

Type Description
DocumentParsingError

the specified document is invalid

Returns:

Type Description
~TBase

an instance of the Model class this method is called on.

Source code in odmantic/model.py
@classmethod
def parse_doc(cls: Type[TBase], raw_doc: Dict) -> TBase:
    """Parse a BSON document into an instance of the Model

    Args:
        raw_doc: document to parse (as Dict)

    Raises:
        DocumentParsingError: the specified document is invalid

    Returns:
        an instance of the Model class this method is called on.
    """
    errors, obj = cls._parse_doc_to_obj(raw_doc)
    if len(errors) > 0:
        raise DocumentParsingError(
            errors=[errors],
            model=cls,
            primary_value=raw_doc.get("_id", "<unknown>"),
        )
    try:
        instance = cls.parse_obj(obj)
    except ValidationError as e:
        raise DocumentParsingError(
            errors=e.raw_errors,  # type: ignore
            model=cls,
            primary_value=raw_doc.get("_id", "<unknown>"),
        )

    return instance

odmantic.model.Model

Class that can be extended to create an ODMantic Model.

Each model will be bound to a MongoDB collection. You can customize the collection name by setting the __collection__ class variable in the model classes.

odmantic.model.EmbeddedModel

Class that can be extended to create an ODMantic Embedded Model.

An embedded document cannot be persisted directly to the database but should be integrated in a regular ODMantic Model.