Skip to content

Add ListSerializer.get_child hook #5847

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

Closed
wants to merge 1 commit into from
Closed
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
13 changes: 10 additions & 3 deletions rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,13 @@ def bind(self, field_name, parent):
super(ListSerializer, self).bind(field_name, parent)
self.partial = self.parent.partial

def get_child(self, instance=None, data=empty):
"""
Hook to override retrieval of the child. By default, this returns the
child instance provided during initialization.
"""
return self.child

def get_initial(self):
if hasattr(self, 'initial_data'):
return self.to_representation(self.initial_data)
Expand Down Expand Up @@ -636,7 +643,7 @@ def to_internal_value(self, data):

for item in data:
try:
validated = self.child.run_validation(item)
validated = self.get_child(data=item).run_validation(item)
except ValidationError as exc:
errors.append(exc.detail)
else:
Expand All @@ -657,7 +664,7 @@ def to_representation(self, data):
iterable = data.all() if isinstance(data, models.Manager) else data

return [
self.child.to_representation(item) for item in iterable
self.get_child(instance=item).to_representation(item) for item in iterable
]

def validate(self, attrs):
Expand All @@ -674,7 +681,7 @@ def update(self, instance, validated_data):

def create(self, validated_data):
return [
self.child.create(attrs) for attrs in validated_data
self.get_child(data=attrs).create(attrs) for attrs in validated_data
]

def save(self, **kwargs):
Expand Down