Makes partial Pydantic models without making fields nullable.
Project description
pydantic-strict-partial
About
Create partial models based on the original Pydantic models.
This makes all the fields optional.
This doesn't make them nullable and doesn't disable validation.
The only thing it does is provide default values for those fields (None
by default),
so you can use model.model_dump(exclude_unset=True)
command to receive specified values only.
The most common use case is a PATCH
request on FastAPI endpoints where you want to allow partial updates.
Installation
pydantic-strict-partial
compatible with Python 3.10+ and Pydantic 2.1+.
Using pip
pip install pydantic-strict-partial
Using poetry
poetry add pydantic-strict-partial
Usage
from typing import Annotated
from annotated_types import Ge
from pydantic import BaseModel
from pydantic_strict_partial import create_partial_model
class UserSchema(BaseModel):
name: str
nickname: str | None
age: Annotated[int, Ge(18)]
UserPartialUpdateSchema = create_partial_model(UserSchema)
assert UserPartialUpdateSchema(age=20).model_dump(exclude_unset=True) == {
'age': 20
}
UserPartialUpdateSchema(name=None) # raises ValidationError
UserPartialUpdateSchema(age=17) # raises ValidationError
There is also possible to specify a limited list of fields to be partial:
UserPartialUpdateSchema = create_partial_model(UserSchema, 'name', 'nickname')
Known limitations
MyPy: "is not valid as a type" error
You may be faced with Variable "UserPartialUpdateSchema" is not valid as a type
error.
There is no good solution for that. But the next approach can be used as a workaround:
class UserPartialUpdateSchema(create_partial_model(UserSchema)): # type: ignore[misc]
pass
Alternatives
pydantic-partial - it makes all fields nullable and disables all validators, which is not suitable for payload validation on PATCH
endpoints.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for pydantic_strict_partial-0.5.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | a311eab55206501901e44a941f62b1ef2598c9ff0a64aaa632522fcab235434a |
|
MD5 | bb05aacce22b0f9a404ceebb65c9fe04 |
|
BLAKE2b-256 | b711f5b9bdb7d00c15111fdb89a47406263c16acbe3eb24b93c4c76c89d7d5e4 |
Hashes for pydantic_strict_partial-0.5.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 34646b4b17e0a9c50ed9766f5c0487e587d0048930b4b423c53442eaf213be32 |
|
MD5 | 277e9824d7bc7a0cd7da1464c99ba543 |
|
BLAKE2b-256 | 1f3b174aafb7eed68e3dc1febf9cb3fe73da68790fd7c9a802fa8b6a584b5316 |