Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs: Adds an example to show how exclude_unset works #1173

Merged
merged 1 commit into from
May 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions docs/docs/guides/response/django-pydantic.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class UserSchema(ModelSchema):

### Making fields optional

Pretty often for PATCH API operations you need to make all fields of your schema optional. To do that you can use config fields_optional
Pretty often for PATCH API operations you need to make all fields of your schema optional. To do that, you can use config fields_optional

```python hl_lines="5"
class PatchGroupSchema(ModelSchema):
Expand All @@ -101,8 +101,27 @@ class PatchGroupSchema(ModelSchema):
fields_optional = '__all__'
```

also you can define just a few optional fields instead of all:
Also, you can define a subset of optional fields instead of `__all__`:

```python
fields_optional = ['description']
```

When you process input data, you need to tell Pydantic to avoid setting undefined fields to `None`:

```python
@api.patch("/patch/{pk}")
def patch(request, pk: int, payload: PatchGroupSchema):

# Notice that we set exclude_unset=True
updated_fields = payload.dict(exclude_unset=True)

obj = MyModel.objects.get(pk=pk)

for attr, value in updated_fields.items():
setattr(obj, attr, value)

obj.save()


```
Loading