Skip to content

# odmantic.field

Used to provide extra information about a field, either for the model schema or complex validation. Some arguments apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`.

Tip

The main additions of ODMantic to the regular pydantic `Field` are the `key_name`, `index`, `unique` and the `primary_field` options.

Warning

If both `default` and `default_factory` are set, an error is raised.

Warning

`primary_field` can't be used along with `key_name` since the key_name will be set to `_id`.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`default` | `Any` | since this is replacing the field’s default, its first argument is used to set the default, use ellipsis (`...`) to indicate the field has no default value | `PydanticUndefined`
`key_name` | `Optional[str]` | the name to use in the the mongo document structure | `None`
`primary_field` | `bool` | this field should be considered as a primary key. | `False`
`index` | `bool` | this field should be considered as an index | `False`
`unique` | `bool` | this field should be considered as a unique index | `False`
`default_factory` | `Optional['NoArgAnyCallable']` | callable that will be called when a default value is needed for this field. | `None`
`title` | `Optional[str]` | can be any string, used in the schema | `None`
`description` | `Optional[str]` | can be any string, used in the schema | `None`
`examples` | `list[Any] | None` | can be any list, used in the schema | `None`
`json_schema_extra` | `JsonDict | Callable[[JsonDict], None] | None` | Any additional JSON schema data for the schema property. | `None`
`const` | `Optional[bool]` | this field is required and must take it's default value | `None`
`gt` | `Optional[float]` | only applies to numbers, requires the field to be "greater than". The schema will have an `exclusiveMinimum` validation keyword | `None`
`ge` | `Optional[float]` | only applies to numbers, requires the field to be "greater than or equal to". The schema will have a `minimum` validation keyword | `None`
`lt` | `Optional[float]` | only applies to numbers, requires the field to be "less than". The schema will have an `exclusiveMaximum` validation keyword | `None`
`le` | `Optional[float]` | only applies to numbers, requires the field to be "less than or equal to" . The schema will have a `maximum` validation keyword | `None`
`multiple_of` | `Optional[float]` | only applies to numbers, requires the field to be "a multiple of ". The schema will have a `multipleOf` validation keyword | `None`
`min_items` | `Optional[int]` | only applies to sequences, requires the field to have a minimum item count. | `None`
`max_items` | `Optional[int]` | only applies to sequences, requires the field to have a maximum item count. | `None`
`min_length` | `Optional[int]` | only applies to strings, requires the field to have a minimum length. The schema will have a `maximum` validation keyword | `None`
`max_length` | `Optional[int]` | only applies to strings, requires the field to have a maximum length. The schema will have a `maxLength` validation keyword | `None`
`regex` | `Optional[str]` | only applies to strings, requires the field match agains a regular expression pattern string. The schema will have a `pattern` validation keyword | `None`

Source code in `odmantic/field.py`

     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

    def Field(
        default: Any = PydanticUndefined,
        *,
        key_name: Optional[str] = None,
        primary_field: bool = False,
        index: bool = False,
        unique: bool = False,
        default_factory: Optional["NoArgAnyCallable"] = None,
        # alias: str = None, # FIXME not supported yet
        title: Optional[str] = None,
        description: Optional[str] = None,
        json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
        const: Optional[bool] = None,
        gt: Optional[float] = None,
        ge: Optional[float] = None,
        lt: Optional[float] = None,
        le: Optional[float] = None,
        multiple_of: Optional[float] = None,
        min_items: Optional[int] = None,
        max_items: Optional[int] = None,
        min_length: Optional[int] = None,
        max_length: Optional[int] = None,
        regex: Optional[str] = None,
        examples: list[Any] | None = None,
    ) -> Any:
        """Used to provide extra information about a field, either for the model schema or
        complex validation. Some arguments apply only to number fields (``int``, ``float``,
         ``Decimal``) and some apply only to ``str``.

        Tip:
            The main additions of ODMantic to the regular pydantic `Field` are the
            `key_name`, `index`, `unique` and the `primary_field` options.

        Warning:
            If both `default` and `default_factory` are set, an error is raised.

        Warning:
            `primary_field` can't be used along with `key_name` since the key_name will be
            set to `_id`.

        Args:
            default: since this is replacing the field’s default, its first argument is
                used to set the default, use ellipsis (``...``) to indicate the field has no
                default value
            key_name: the name to use in the the mongo document structure
            primary_field: this field should be considered as a primary key.
            index: this field should be considered as an index
            unique: this field should be considered as a unique index
            default_factory: callable that will be called when a default value is needed
                for this field.
            title: can be any string, used in the schema
            description: can be any string, used in the schema
            examples: can be any list, used in the schema
            json_schema_extra: Any additional JSON schema data for the schema property.
            const: this field is required and *must* take it's default value
            gt: only applies to numbers, requires the field to be "greater than". The
                schema will have an ``exclusiveMinimum`` validation keyword
            ge: only applies to numbers, requires the field to be "greater than or equal
                to". The schema will have a ``minimum`` validation keyword
            lt: only applies to numbers, requires the field to be "less than". The schema
                will have an ``exclusiveMaximum`` validation keyword
            le: only applies to numbers, requires the field to be "less than or equal to"
                . The schema will have a ``maximum`` validation keyword
            multiple_of: only applies to numbers, requires the field to be "a multiple of
                ". The schema will have a ``multipleOf`` validation keyword
            min_items: only applies to sequences, requires the field to have a minimum
                item count.
            max_items: only applies to sequences, requires the field to have a maximum
                item count.
            min_length: only applies to strings, requires the field to have a minimum
                length. The schema will have a ``maximum`` validation keyword
            max_length: only applies to strings, requires the field to have a maximum
                length. The schema will have a ``maxLength`` validation keyword
            regex: only applies to strings, requires the field match agains a regular
                expression pattern string. The schema will have a ``pattern`` validation
                keyword

        <!---
        # noqa: DAR201
        # noqa: DAR003
        # noqa: DAR401
        # noqa: DAR101
        -->
        """
        # Perform casts on optional fields to avoid incompatibility due to the strict
        # optional mypy setting
        # TODO: add remaining validation fields from pydantic
        pydantic_field = PDField(
            default,
            default_factory=default_factory,
            # alias=alias,  # FIXME check aliases compatibility
            title=cast(str, title),
            description=cast(str, description),
            examples=examples,
            json_schema_extra=json_schema_extra,
            const=cast(bool, const),
            gt=cast(float, gt),
            ge=cast(float, ge),
            lt=cast(float, lt),
            le=cast(float, le),
            multiple_of=cast(float, multiple_of),
            min_items=cast(int, min_items),
            max_items=cast(int, max_items),
            min_length=cast(int, min_length),
            max_length=cast(int, max_length),
            regex=cast(str, regex),
        )
        if primary_field:
            if key_name is not None and key_name != "_id":
                raise ValueError(
                    "cannot specify a primary field with a custom key_name,"
                    "key_name='_id' enforced"
                )
            else:
                key_name = "_id"
        elif key_name == "_id":
            raise ValueError(
                "cannot specify key_name='_id' without defining the field as primary"
            )

        return ODMFieldInfo(
            pydantic_field_info=pydantic_field,
            primary_field=primary_field,
            key_name=key_name,
            index=index,
            unique=unique,
        )