Skip to content
Open
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
9 changes: 7 additions & 2 deletions docs/api-guide/serializers.md
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,8 @@ Here's an example of how you might choose to implement multiple updates:
def update(self, instance, validated_data):
# Maps for id->instance and id->data item.
book_mapping = {book.id: book for book in instance}
data_mapping = {item['id']: item for item in validated_data}
data_mapping = {item['id']: item for item in validated_data if 'id' in item}
new_items = [item for item in validated_data if 'id' not in item]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this could be a single loop instead of two separate comprehensions, to avoid iterating validated_data twice — e.g.:

data_mapping = {}
new_items = []
for item in validated_data:
    if 'id' in item:
        data_mapping[item['id']] = item
    else:
        new_items.append(item)


# Perform creations and updates.
ret = []
Expand All @@ -816,6 +817,9 @@ Here's an example of how you might choose to implement multiple updates:
else:
ret.append(self.child.update(book, data))

for data in new_items:
ret.append(self.child.create(data))

# Perform deletions.
for book_id, book in book_mapping.items():
if book_id not in data_mapping:
Expand All @@ -826,7 +830,8 @@ Here's an example of how you might choose to implement multiple updates:
class BookSerializer(serializers.Serializer):
# We need to identify elements in the list using their primary key,
# so use a writable field here, rather than the default which would be read-only.
id = serializers.IntegerField()
# The id is optional so that new items (without an id) can be created.
id = serializers.IntegerField(required=False)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense given the new create path.

...

class Meta:
Expand Down
Loading