Skip to content

Commit 64bee7f

Browse files
authored
Improve docstring for get_serializer to clarify behavior (#9870)
1 parent 04b0d7f commit 64bee7f

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

rest_framework/serializers.py

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,18 @@ def __new__(cls, name, bases, attrs):
312312

313313

314314
def as_serializer_error(exc):
315+
"""
316+
Coerce validation exceptions into a standardized serialized error format.
317+
318+
This function normalizes both Django's `ValidationError` and REST
319+
framework's `ValidationError` into a dictionary structure compatible
320+
with serializer `.errors`, ensuring all values are represented as
321+
lists of error details.
322+
323+
The returned structure conforms to the serializer error contract:
324+
- Field-specific errors are returned as '{field-name: [errors]}'
325+
- Non-field errors are returned under the 'NON_FIELD_ERRORS_KEY'
326+
"""
315327
assert isinstance(exc, (ValidationError, DjangoValidationError))
316328

317329
if isinstance(exc, DjangoValidationError):
@@ -815,22 +827,29 @@ def errors(self):
815827

816828
def raise_errors_on_nested_writes(method_name, serializer, validated_data):
817829
"""
818-
Give explicit errors when users attempt to pass writable nested data.
830+
Enforce explicit handling of writable nested and dotted-source fields.
819831
820-
If we don't do this explicitly they'd get a less helpful error when
821-
calling `.save()` on the serializer.
832+
This helper raises clear and actionable errors when a serializer attempts
833+
to perform writable nested updates or creates using the default
834+
`ModelSerializer` behavior.
822835
823-
We don't *automatically* support these sorts of nested writes because
824-
there are too many ambiguities to define a default behavior.
836+
Writable nested relationships and dotted-source fields are intentionally
837+
unsupported by default due to ambiguous persistence semantics. Developers
838+
must either:
839+
- Override the `.create()` / `.update()` methods explicitly, or
840+
- Mark nested serializers as `read_only=True`
841+
842+
This check is invoked internally by default `ModelSerializer.create()`
843+
and `ModelSerializer.update()` implementations.
825844
826845
Eg. Suppose we have a `UserSerializer` with a nested profile. How should
827846
we handle the case of an update, where the `profile` relationship does
828847
not exist? Any of the following might be valid:
829-
830848
* Raise an application error.
831849
* Silently ignore the nested part of the update.
832850
* Automatically create a profile instance.
833851
"""
852+
834853
ModelClass = serializer.Meta.model
835854
model_field_info = model_meta.get_field_info(ModelClass)
836855

0 commit comments

Comments
 (0)