From 1280bd3c80ae81a066663cdd265121cfef3193af Mon Sep 17 00:00:00 2001 From: Christian Hattemer Date: Fri, 25 Oct 2024 16:51:08 +0200 Subject: [PATCH] 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. --- pydantic_partial/partial.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/pydantic_partial/partial.py b/pydantic_partial/partial.py index 7e6868c..69cf1b4 100644 --- a/pydantic_partial/partial.py +++ b/pydantic_partial/partial.py @@ -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: @@ -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