Skip to content

Commit

Permalink
Merge pull request #1173 from benjaoming/docs-fix-exclude_unset
Browse files Browse the repository at this point in the history
Docs: Adds an example to show how exclude_unset works
  • Loading branch information
vitalik authored May 24, 2024
2 parents e7dc90e + bdb1f27 commit bbf1b4b
Showing 1 changed file with 21 additions and 2 deletions.
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()


```

0 comments on commit bbf1b4b

Please sign in to comment.