Skip to content

Commit f9f3e95

Browse files
Udit PrabhakarUdit Prabhakar
authored andcommitted
Docs: Explain object-level validation during partial updates (PATCH) #3070
1 parent 385df20 commit f9f3e95

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

docs/api-guide/serializers.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,26 @@ To do any other validation that requires access to multiple fields, add a method
214214
raise serializers.ValidationError("finish must occur after start")
215215
return data
216216

217+
!!! note
218+
**Object-Level Validation and Partial Updates**
219+
220+
When performing a **partial update** (`PATCH`), the `data` dictionary passed to the `validate()` method will **only contain the fields** provided in the request. If your validation logic depends on multiple fields, you must account for cases where some fields are missing from `data`.
221+
222+
To access fields not included in the partial update, you should retrieve them from the existing object instance using `self.instance`:
223+
224+
```python
225+
def validate(self, data):
226+
# Check if 'status' is being updated, or use the existing value
227+
status = data.get('status', self.instance.status)
228+
229+
# Check if 'price' is being updated, or use the existing value
230+
price = data.get('price', self.instance.price)
231+
232+
if status == 'active' and price <= 0:
233+
raise serializers.ValidationError("Active products must have a price.")
234+
return data
235+
```
236+
217237
#### Validators
218238

219239
Individual fields on a serializer can include validators, by declaring them on the field instance, for example:

0 commit comments

Comments
 (0)