Skip to content

Commit 1280bd3

Browse files
author
Christian Hattemer
committed
Allow to keep the types as they were and just add a default value
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.
1 parent a39b984 commit 1280bd3

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

pydantic_partial/partial.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ def create_partial_model(
4141
base_cls: type[SelfT],
4242
*fields: str,
4343
recursive: bool = False,
44+
optional: bool = True,
4445
) -> type[SelfT]:
4546
# Convert one type to being partial - if possible
4647
def _partial_annotation_arg(field_name_: str, field_annotation: type) -> type:
@@ -104,8 +105,15 @@ def _partial_annotation_arg(field_name_: str, field_annotation: type) -> type:
104105
# Construct new field definition
105106
if field_name in fields_:
106107
if model_compat.is_model_field_info_required(field_info):
108+
# Allow to keep the types as they were and just add a
109+
# default value
110+
if optional:
111+
annotation = Optional[field_annotation]
112+
else:
113+
annotation = field_annotation
114+
107115
optional_fields[field_name] = (
108-
Optional[field_annotation],
116+
annotation,
109117
model_compat.copy_model_field_info(
110118
field_info,
111119
default=None, # Set default to None

0 commit comments

Comments
 (0)