Skip to content

Commit

Permalink
feat: allow specifying required fields
Browse files Browse the repository at this point in the history
  • Loading branch information
ADR-007 committed Dec 3, 2024
1 parent 63c5fc1 commit cd9979b
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ There is also possible to specify a limited list of fields to be partial:
UserPartialUpdateSchema = create_partial_model(UserSchema, 'name', 'nickname')
```

Or to make all fields partial except for the specified ones:

```python
UserPartialCreateSchema = create_partial_model(UserSchema, required_fields=['age'])
```

## Known limitations

#### MyPy: "is not valid as a type" error
Expand Down
6 changes: 6 additions & 0 deletions pydantic_strict_partial/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,24 @@
def create_partial_model(
model: type[T],
*optional_fields: str,
required_fields: list[str] | None = None,
default_value: Any = None, # noqa: ANN401
) -> type[T]:
"""Create a partial model from the given model class.
:param model: The model class to create a partial model from.
:param optional_fields: The fields to make optional.
If None, all fields will be made optional.
:param required_fields: The fields to make required.
If None, no fields will be made required.
:param default_value: The default value to use for optional fields.
:return: The partial model class.
"""
fields = {}
for field in optional_fields or model.model_fields.keys():
if required_fields and field in required_fields:
continue

field_info = model.model_fields[field]

fields[field] = (
Expand Down
16 changes: 16 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,19 @@ class Model(BaseModel):

with pytest.raises(ValidationError):
model_partial_class(required="value")


def test_make_some_fields_required() -> None:
class Model(BaseModel):
required: str
required2: str

model_partial_class = create_partial_model(
Model,
required_fields=["required"],
)

model_partial_class(required="value")

with pytest.raises(ValidationError):
model_partial_class(required2="value")

0 comments on commit cd9979b

Please sign in to comment.