Pydantic Collections
Pydantic-collections provides the `BaseCollectionModel` class, which allows for the manipulation and validation of collections of Pydantic models. It supports various Pydantic-compatible types within its collections. The library is actively maintained, with releases often corresponding to updates in the Pydantic ecosystem, and the current version is 0.6.0.
Warnings
- breaking Version `0.5.0` of `pydantic-collections` introduced support for Pydantic V2. Projects upgrading Pydantic from V1 to V2 must also upgrade `pydantic-collections` to `v0.5.0` or newer. This also implies adapting to Pydantic V2's own breaking changes, such as method renames (`.dict()` to `.model_dump()`, `.json()` to `.model_dump_json()`) and configuration changes (e.g., `Config` inner class to `model_config` attribute).
- gotcha By default, `BaseCollectionModel` enforces strict assignment validation. Attempting to append or assign raw dictionaries or objects that are not already instances of the collection's base model will raise a `ValidationError`.
- gotcha The `pydantic-collections` library declares a dependency on `pydantic>=1.8.2,<3.0`. Be cautious when pinning `pydantic` in your project, especially to `<2`, as this can cause conflicts with `pydantic-collections` versions expecting V2 features or if `pydantic-collections` itself updates to explicitly require Pydantic V2+ in a future major version.
Install
-
pip install pydantic-collections
Imports
- BaseCollectionModel
from pydantic_collections import BaseCollectionModel
Quickstart
from datetime import datetime
from pydantic import BaseModel
from pydantic_collections import BaseCollectionModel
class User(BaseModel):
id: int
name: str
birth_date: datetime
class UserCollection(BaseCollectionModel[User]):
pass
user_data = [
{'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'},
{'id': 2, 'name': 'Balaganov', 'birth_date': '2020-04-01T12:59:59'},
]
users = UserCollection(user_data)
print(users)
# For Pydantic v2.x, use model_dump() and model_dump_json()
print(users.model_dump())
print(users.model_dump_json())