ElasticModel
ElasticModel is a wrapper around pydantic.BaseModel(v2) designed to simplify working with partial (projected) data from databases or APIs.
Key advantage: nested models (“model-in-model”) work even when not all required fields are loaded. Methods remain usable at any level and operate on the data that is loaded.
Pydantic’s
model_validate()requires all required fields.model_construct()allows partials but keeps nested dicts as raw dicts. ElasticModel combines the best of both.
Core features of ElasticModel:
- ✅ Inherits the behavior of
pydantic.BaseModel: code written forBaseModelkeeps working after you replace it withElasticModel, and the new features come as separateelastic_*methods. The few deliberate differences are listed in Differences from BaseModel. - ✅ Allows creating models from incomplete data, providing full access — read fields, call methods, even on nested models.
- ✅ Avoids the need for declaring a bunch of
Optionalfields. - ✅ Supports dynamic unknown fields — stored in
self.elastic_extra, a dictionary for unprocessed data. - ✅ Ensures strict access: only loaded fields can be accessed. Trying to access an unloaded field will raise
NotLoadedFieldError. - ✅ Supports recursive creation of nested models.
- ✅ Provides "shallow" or "deep" checks for required fields at any time (on demand).
ElasticModel combines the best of BaseModel.model_validate (structured/nested models) and BaseModel.model_construct (creation without validation), adding new flexibility for working with partial data — without overloading your codebase with Optional fields.
🌐Переклад тут🔱 ElasticModel — це `pydantic.BaseModel`(v2), який надає ... та спрощує...
... спрощує роботу з частковими (проекційними) даними з баз даних або API.Основна перевага — підтримка вкладених моделей ("модель у моделі") без необхідності завантаження всіх полів. Незважаючи на це, методи моделі залишаються доступними на всіх рівнях і працюють із тими даними, які були завантажені.
⚠️У Pydantic така поведінка була б неможливою, оскільки він вимагає наявності всіх полів.
Основні можливості ElasticModel:
- ✅ Наслідує поведінку
pydantic.BaseModel: код, написаний підBaseModel, працює без змін після заміни наElasticModel, а нове доступне окремими методамиelastic_*. Свідомі відмінності перелічені в розділі Differences from BaseModel. - ✅ Дозволяє створювати моделі з неповними даними й отримувати повний доступ — читати поля, викликати методи, навіть на вкладених моделях.
- ✅ Не потребує великої кількості полів типу
Optional. - ✅ Підтримує динамічні (неописані) поля — вони зберігаються в
self.elastic_extra, словнику для необроблених даних. - ✅ Гарантує контроль доступу: можна звертатись лише до завантажених полів. Спроба доступу до незавантаженого поля викличе
NotLoadedFieldError. - ✅ Підтримує рекурсивне створення вкладених моделей.
- ✅ Дозволяє виконувати поверхневу або глибоку перевірку обов’язкових полів у будь-який момент (на вимогу користувача).
ElasticModel поєднує найкраще з BaseModel.model_validate (структуровані/вкладені моделі) та BaseModel.model_construct (створення без валідації), додаючи нову гнучкість у роботі з частковими даними — без перевантаження кодової бази полями Optional.
Install
pip install elasticmodel
https://pypi.org/project/elasticmodel/
Requires Python 3.11+. Python 3.10 is not blocked, but it is not supported: a model name written as a string inside a builtin generic is not resolved there. See Python 3.10.
Quick start
💡 ElasticModel.elastic_create validation modes
validate=True- All values are coerced to their declared types and validated by Pydantic. The only exception is nestedElasticModel, which are built with support for "partial data".validate=False- No coercion or validation is applied — values are kept as-is. The only exceptions is nestedBaseModelandElasticModel, which are built with support for "partial data".
>>> from typing import Annotated
>>> from datetime import datetime
>>> from pydantic import Field, EmailStr
>>> from elasticmodel import ElasticModel, NotLoadedFieldError
>>> class Created(ElasticModel):
... at: str
... by: str
...
... def datetime_from_at(self) -> datetime:
... return datetime.strptime(self.at, "%Y-%m-%d")
...
>>> class User(ElasticModel):
... id: str = Field(alias="_id") # "_id" maps onto "id" by default, as in pydantic
... first_name: Annotated[str, Field(min_length=2)]
... last_name: str
... email: EmailStr
... created: Created
... updated: Created
...
... def welcome(self) -> str:
... return f"Hi {self.first_name} {self.last_name}! Joined at {self.created.datetime_from_at()}"
...
>>> # Build from a projection (partial dict): "by" is missing in both nested dicts,
>>> # and "external_value" is a key the model does not declare.
>>> doc = {
... "_id": "u1",
... "first_name": "Ann",
... "last_name": "Lee",
... "email": "ann@example.com",
... "created": {"at": "2025-08-15"},
... "updated": {"at": "2099-01-10"},
... "external_value": 1,
... }
>>> # --------MAIN CONSTRUCTOR-------
>>> u = User.elastic_create(doc)
>>> # -------------------------------
>>> u.id # Alias works
'u1'
>>> # .elastic_extra is a plain dict holding every unknown key, kept without validation
>>> u.elastic_extra
{'external_value': 1}
>>> # The nested model is constructed, so its methods work on the data that IS loaded
>>> u.created.datetime_from_at()
datetime.datetime(2025, 8, 15, 0, 0)
>>> print(u.welcome())
Hi Ann Lee! Joined at 2025-08-15 00:00:00
>>> # Accessing a declared but not loaded field raises NotLoadedFieldError
>>> u.created.by
Traceback (most recent call last):
NotLoadedFieldError: Field 'by' is declared in Created but was not loaded into this instance
>>> # .elastic_is_loaded(name) - safe check for field presence, it never raises
>>> u.created.elastic_is_loaded("by")
False
>>> u.created.by = "system" # Assigning to a field marks it as loaded
>>> u.created.elastic_is_loaded("by")
True
>>> # Choose the validation depth when you need it.
>>> # shallow (recursive=False) does not descend into nested models
>>> u.elastic_is_valid(recursive=False)
(True, [])
>>> # deep (recursive=True) descends and finds the field still missing in "updated"
>>> u.elastic_is_valid(recursive=True)
(False, ['updated.by'])
>>> # Produce a fully validated instance of the same model class (Self), or raise ValidationError
>>> u.updated.by = "user" # Fill the gap first, otherwise validation raises
>>> validated = u.elastic_get_validated_model(recursive=True)
>>> type(validated) is User
True
Comparing .elastic_create to .model_validate and .model_construct from pydantic
>>> from datetime import datetime
>>> from pydantic import BaseModel, EmailStr, ValidationError
>>> from elasticmodel import ElasticModel
>>> # Three ways to build an object from the same partial data:
>>> # 1. pydantic.BaseModel.model_validate
>>> # 2. pydantic.BaseModel.model_construct
>>> # 3. elasticmodel.ElasticModel.elastic_create
>>> # Two identical model pairs, one built on BaseModel and one on ElasticModel:
>>> class CreatedPydantic(BaseModel):
... at: str
... by: str
... def datetime_from_at(self) -> datetime:
... return datetime.strptime(self.at, "%Y-%m-%d")
...
>>> class UserPydantic(BaseModel):
... email: EmailStr
... created: CreatedPydantic
...
>>> class CreatedElastic(ElasticModel):
... at: str
... by: str
... def datetime_from_at(self) -> datetime:
... return datetime.strptime(self.at, "%Y-%m-%d")
...
>>> class UserElastic(ElasticModel):
... email: EmailStr
... created: CreatedElastic
...
>>> # Equally limited data, but enough for the actions we need: "by" is missing.
>>> partial_data = {"email": "a@b.com", "created": {"at": "2025-08-15"}}
>>> # 1. pydantic.model_validate -> raises immediately
>>> UserPydantic.model_validate(partial_data)
Traceback (most recent call last):
ValidationError: 1 validation error for UserPydantic
>>> # 2. pydantic.model_construct -> does not validate, but keeps nested dicts
>>> user_construct = UserPydantic.model_construct(**partial_data)
>>> isinstance(user_construct.created, dict) # a raw dict, so CreatedPydantic methods are not there
True
>>> user_construct.created.datetime_from_at()
Traceback (most recent call last):
AttributeError: 'dict' object has no attribute 'datetime_from_at'
>>> # 3. ElasticModel.elastic_create -> no instant failure, and nested models are built
>>> user_elastic = UserElastic.elastic_create(partial_data)
>>> isinstance(user_elastic.created, CreatedElastic)
True
>>> print(user_elastic.created.datetime_from_at())
2025-08-15 00:00:00
Summary:
model_validate: full validation + nested building, but no partialsmodel_construct: partials OK, but nested dicts remain dictselastic_create: partials OK + nested building + strict read access + shallow/deep validation
Key features
-
Partial construction:
elastic_create(data, validate=True, strict_validate=False, defaults=False)- Accepts dicts with missing and extra keys
- Validates/coerces each value by the field rules, as
model_validatedoes: the type hint,Field(...)constraints and the model config (strict,str_strip_whitespace,arbitrary_types_allowed, …) - Unknown keys are captured in
model.elastic_extra - Tracks actually loaded fields in
model.elastic_loaded_fields defaults=Trueappliesdefault/default_factoryto missing fields; those fields are not counted as loaded, soelastic_is_loadedstill reportsFalsefor them. A default of a field withvalidate_defaultis validated, as in pydanticstrict_validate=Truevalidates in pydantic strict mode, without coercion:"5"is not turned into5. It turns validation on even withvalidate=False, nestedBaseModelincludeddefaultsandstrict_validatereach nestedElasticModelat every level: direct fields, containers and the branches ofOptional/Unionfields
-
Strict read access
- Accessing an unloaded declared field raises
NotLoadedFieldError - System attributes and dunders are not intercepted
- Three limits of this guarantee, all of them by design:
NotLoadedFieldErrorsubclassesAttributeError, sohasattr(model, "field")returnsFalseandgetattr(model, "field", fallback)returns the fallback. Both silence the violation instead of surfacing it- A field whose name shadows a
BaseModelattribute (copy,json, …) is not covered: the normal attribute lookup finds the inherited member, so the check never runs. Pydantic warns about such shadowing when the class is declared - A field filled by
defaults=Truereads back its default value, even thoughelastic_is_loadedreportsFalsefor it
- Accessing an unloaded declared field raises
-
Shallow vs Deep validation
- Shallow: keep existing nested instances, fast
- Deep: fully materialize to plain structures and validate everything
-
Nested models and containers
- Nested
ElasticModelfields are built viaelastic_create list/set/tupleitems are coerced recursively (whenvalidate=True)dict[K, V]keys and values are validated (whenvalidate=True)OptionalandUnionfields get partial models too, see Optional and Union fields
- Nested
API snapshot
ElasticModel.elastic_create(data: dict, validate: bool = True, strict_validate: bool = False, defaults: bool = False) -> Selfmodel.elastic_extra -> dict[str, Any]— a shallow copy: changing it does not change the model, but nested values are shared with itmodel.elastic_loaded_fields -> set[str]— a copy, so mutating it does not change the model. For a model built by pydantic validation (constructor,model_validate,elastic_get_validated_model) these are the fields present in the validation input, so a field that a default filled in the source model counts as loaded in the copy returned byelastic_get_validated_modelmodel.elastic_is_loaded(name: str) -> boolmodel.elastic_is_valid(recursive: bool = True) -> tuple[bool, list[str]]— paths use field names, not aliases:'created.by'model.elastic_get_validated_model(recursive: bool = True) -> Self— the copy keeps.elastic_extraat every nesting level- Assignment marks fields as loaded:
model.field = value
Defaults and config
ElasticModel recommends the following default values for pydantic.ConfigDict:
extra='ignore'— extra keys are ignored by Pydantic but manually collected into.elastic_extrarevalidate_instances='never'— nested model instances are not revalidated automatically (important for shallow validation)
Aliases follow the same config rules as in pydantic:
- A key matching a field's alias fills that field —
validate_by_alias, on by default. - The field's own name is accepted for an aliased field only with
validate_by_name=True(or the olderpopulate_by_name=True). - With
validate_by_alias=Falsethe alias is no longer accepted. - If both the alias and the field name arrive, the alias wins.
- Every key that did not fill a field — unknown to the model, disallowed by the config, or beaten by the alias — lands in
.elastic_extra. Withextra='allow'it also lands inmodel_extra, exactly as pydantic puts it there.
A nested BaseModel built with validate=False uses the same rules. It has no .elastic_extra, so a key that did not fill a field goes to model_extra with extra='allow' and is dropped otherwise.
Optional and Union fields
elastic_create builds a partial model inside Optional and Union fields too. Pydantic cannot do this: it validates a Union branch in full, so partial data fits no branch.
Optional[X]works exactly likeX: a partial dict, a list of partial dicts, a discriminatedUnioninside.- Discriminated
Union(Field(discriminator=...)orDiscriminator(...)) picks the branch by the tag in the data, using the tag table pydantic itself builds. Only that branch is built:model_post_initand validators of the other branches never run. Without a tag, or with an unknown one, the value stays as is: with validation pydantic raisesunion_tag_not_found/union_tag_invalid, without validation the field keeps the dict. - Plain
Unionpicks the branch by a rule close to pydantic's smart mode. The rule is the same forvalidate=Trueandvalidate=False: the present values are checked even without validation, but they land in the model as is.- If a non-model branch accepts a dict (
dict,Any, aTypedDict), pydantic decides and the value is passed on as is. - A model branch drops out if it rejects one of the present values, if the data fills none of its fields, or if it has
extra='forbid'and the data has keys it does not know. - Of the rest, complete branches (all required fields present) come first, then the branch with more filled fields, then the leftmost one.
- If every branch rejects the values, the first one is built: with validation it raises the same error as a direct field of that class, without validation it gets the values as is.
- If a non-model branch accepts a dict (
defaultsandstrict_validatereach the chosen branch, as in a direct field.- A plain
BaseModelbranch with validation is left to pydantic, as a directBaseModelfield is: it cannot take partial data anyway, so the result and the errors are exactly pydantic's.
For partial data prefer a discriminated Union: the tag leaves nothing to guess.
>>> from typing import Literal, Union
>>> class Card(ElasticModel):
... kind: Literal["card"]
... pan: str
... holder: str
...
>>> class Bank(ElasticModel):
... kind: Literal["bank"]
... iban: str
...
>>> class Payment(ElasticModel):
... method: Annotated[Union[Card, Bank], Field(discriminator="kind")]
...
>>> p = Payment.elastic_create({"method": {"kind": "card", "holder": "Ann"}})
>>> type(p.method).__name__
'Card'
>>> sorted(p.method.elastic_loaded_fields)
['holder', 'kind']
Differences from BaseModel
An ElasticModel built the usual pydantic way (constructor, model_validate, model_construct, copies) behaves exactly like a BaseModel. The differences below are deliberate.
Extensions:
extra='forbid'—elastic_createdoes not reject unknown keys: they land in.elastic_extra. Pydantic validation (constructor,model_validate) still rejects them.==also compares.elastic_extra: models with the same data but different.elastic_extraare not equal.elastic_get_validated_modelkeeps.elastic_extrain the copy, so a valid model equals its validated copy.- Partial data in
Optional/Unionfields, see Optional and Union fields. Data that pydantic accepts gets the same branch, except for the plainUnioncases below.
Limits of the plain Union rule:
- Exactness is not used.
Union[IntX, StrX]with{"x": "1"}givesIntX, the first branch that accepts"1"; pydantic givesStrX, the exact type match. - Class validators of a branch take no part in the choice. If an after-validator of
VArejects the data inUnion[VA, VB], the result isVAand then the validator error; pydantic falls back toVB. - The check of present values runs
Annotatedvalidators of branch fields, and builds the nested models of a branch, so theirwrap/aftervalidators andmodel_post_initrun too — even withvalidate=False. This applies only to a plainUnionwith several model branches. Such code must not raise anything but a validation error, and must not read fields that may be unloaded: any other exception,NotLoadedFieldErrorincluded, propagates fromelastic_createeven withvalidate=False. - Data that is complete for another branch goes to that branch, as in pydantic. In
Union[Long, Short], data with every fieldShortneeds givesShort, even if you meant a partialLong. - A discriminated
Unionused as a member of a widerUnion(notOptional) is treated as plain: its tag does not pick the branch, though aLiteraltag still rules out the other branches in the check. - Only a dict value picks a branch. Any other value in a
Unionthat is notOptionalis passed to pydantic as is, soUnion[list[Item], int]with a list of partial dicts fails as in pydantic.Optional[list[Item]]works.
Limits of elastic_create:
- Class validators (
@field_validator,@model_validator) do not run. They run inelastic_get_validated_model()andmodel_validate(). One exception comes from pydantic itself: a nested model is built first and then passed into its field as a ready instance, and pydantic runs@model_validator(mode='wrap')andmode='after'on any instance in a field. So such a validator on a nested model runs on the partial instance and must not read fields that may be unloaded. - On invalid data it raises
ValidationErrorfor the first invalid value only, and the error does not name the field. - A
@computed_fieldthat reads an unloaded field raisesNotLoadedFieldError, and so doesmodel_dump(), which serializes the computed field. - A field named
clsis not supported:elastic_createbuilds the model with pydantic'smodel_construct(cls, ...), which cannot take such a field either, so it raisesTypeError. An unknown data keyclsworks as any other unknown key.
Limit of elastic_loaded_fields:
- With
extra='allow', pydantic validation puts a disallowed key that carries a field name into bothmodel_extraandmodel_fields_set. So in a model built by the constructor ormodel_validate, that field counts as loaded even though it holds its default. Models built byelastic_createandelastic_get_validated_modelare not affected.
Python 3.10
Python 3.10 is not blocked, but it is not supported. Known issue: a model name written as a string inside a builtin generic is not resolved, so elastic_create raises PydanticUserError:
class Node(ElasticModel):
name: str
children: list["Node"] = [] # Python 3.10: elastic_create -> PydanticUserError
On 3.10 use List["Node"] from typing, or put from __future__ import annotations at the top of the module.
Metadata
Release files for elasticmodel 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| elasticmodel-0.4.0.tar.gz | 58.2 kB | With provenance | Details for elasticmodel-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| elasticmodel-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for elasticmodel-0.4.0-py3-none-any.whl |
Total release size: 85.3 kB
Release files / elasticmodel-0.4.0.tar.gz
| Download URL | elasticmodel-0.4.0.tar.gz |
|---|---|
| Size | 58.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1c2d8dd16553f726cabf2ca1d0d5838b9edd5a61b21d98d6a1e03ff49560e1aa
|
|
BLAKE2b-256 checksum How to use checksums |
05307f52b534b36da20c42a375f87c3d1042b89c72f571780a4091a96ad7aea4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 25, 2026.
Transparency logRelease files / elasticmodel-0.4.0-py3-none-any.whl
| Download URL | elasticmodel-0.4.0-py3-none-any.whl |
|---|---|
| Size | 27.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
61b912a91570cd1dad74ea190878b1ecf8b8fb96e2d698a7a8eb3b4c2bcac9cd
|
|
BLAKE2b-256 checksum How to use checksums |
b702f3449348bd89ae88caa8b151a8918e269df98e8880b966a79f65c10ac492
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 25, 2026.
Transparency logSecurity for elasticmodel 0.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for elasticmodel-0.4.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 25, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.