Skip to content

Commit

Permalink
Allow to keep the types as they were and just add a default value
Browse files Browse the repository at this point in the history
It's still possible to omit all unchanged fields in PATCH requests, but
for fields that are given Pydantic will reject data that specifies an
explicit null for fields that aren't optional in the full model.

This is useful when using the package with SQLModel. Without this
feature the client could try to assign a NULL value to a column with a
NOT NULL constraint, which would raise an IntegrityError.
  • Loading branch information
Christian Hattemer committed Dec 5, 2024
1 parent a39b984 commit 1280bd3
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion pydantic_partial/partial.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def create_partial_model(
base_cls: type[SelfT],
*fields: str,
recursive: bool = False,
optional: bool = True,
) -> type[SelfT]:
# Convert one type to being partial - if possible
def _partial_annotation_arg(field_name_: str, field_annotation: type) -> type:
Expand Down Expand Up @@ -104,8 +105,15 @@ def _partial_annotation_arg(field_name_: str, field_annotation: type) -> type:
# Construct new field definition
if field_name in fields_:
if model_compat.is_model_field_info_required(field_info):
# Allow to keep the types as they were and just add a
# default value
if optional:
annotation = Optional[field_annotation]
else:
annotation = field_annotation

optional_fields[field_name] = (
Optional[field_annotation],
annotation,
model_compat.copy_model_field_info(
field_info,
default=None, # Set default to None
Expand Down

0 comments on commit 1280bd3

Please sign in to comment.