Skip to content
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

BookListSerializer example for create case is still flawed #9469

Open
mangelozzi opened this issue Jul 14, 2024 · 0 comments
Open

BookListSerializer example for create case is still flawed #9469

mangelozzi opened this issue Jul 14, 2024 · 0 comments

Comments

@mangelozzi
Copy link

This example at https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-update

class BookListSerializer(serializers.ListSerializer):
    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}

        # Perform creations and updates.
        ret = []
        for book_id, data in data_mapping.items():
            book = book_mapping.get(book_id, None)
            if book is None:
                ret.append(self.child.create(data))
            else:
                ret.append(self.child.update(book, data))

The update method handles update/insertions/deletes. In the insertion case, because an id key value pair will not exist in validated data, so this line:

 data_mapping = {item['id']: item for item in validated_data}

Will fail at item['id'], maybe it should be item.get('id'), but then maybe the rest of it might have to change too, e.g.:

         for book_id, data in data_mapping.items():
            if not book_id:
                ret.append(self.child.create(data))
            else:
                object = object_mapping.get(book_id, None)
                ret.append(self.child.update(object, data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant