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

Improve ListSerializer #9244

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

felipediel
Copy link

Description

#8979 prevents list serializers from having data and instances with different lengths:

https://github.com/encode/django-rest-framework/pull/8979/files#diff-c33f1f011c9f5cf3ed1357b809ebf2b4ed0b808b227c6c007291bf9b259422ecR612-R617

This design choice breaks some use cases. Let's say we want the list serializer to delete from queryset all elements that are not provided in the data during an update. The queryset will be bigger than the data in this case:

# Example: serializer that will break after #8979

class BankBulkUpdateSerializer(serializers.ListSerializer):
    """Bank bulk update serializer."""

    def update(
        self,
        instance: models.QuerySet[Bank],
        validated_data: list[OrderedDict],
    ) -> list[Bank]:
        """Bulk update banks."""
        bank_dict = {bank.pk: bank for bank in instance}
        banks_to_create: list[Bank] = []
        banks_to_update: list[Bank] = []
        banks_created: list[Bank] = []
        banks_updated: list[Bank] = []
        bank_pks_to_keep: list[int] = []

        for bank_data in validated_data:
            bank_id = bank_data.get("id")
            bank = bank_dict.get(bank_id) if bank_id is not None else None

            if bank is not None:
                for attr, value in bank_data.items():
                    setattr(bank, attr, value)
                banks_to_update.append(bank)
                bank_pks_to_keep.append(bank.pk)

            else:
                bank = Bank(**bank_data)
                banks_to_create.append(bank)

        with db_transaction.atomic():
            instance.exclude(pk__in=bank_pks_to_keep).delete()

            if banks_to_update:
                update_fields = ["name", "compe", "ispb", "website"]
                Bank.objects.bulk_update(banks_to_update, update_fields)
                banks_updated = banks_to_update

            if banks_to_create:
                banks_created: list[Bank] = Bank.objects.bulk_create(
                    banks_to_create
                )

        return sorted(banks_created + banks_updated, key=lambda a: a.name)

The intention of the original PR is good, it solves the problem of not passing initial data and instances to child serializers correctly. But instead of indexing, it's better to relate the elements by id, so we can have different lengths. This PR addresses the issue.

refs #8926 #8979

Comment on lines +698 to +700
if not self.instance and self.parent and self.parent.instance:
rel_mgr = get_attribute(self.parent.instance, self.source_attrs)
self.instance = rel_mgr.all() if rel_mgr else None
Copy link
Author

Choose a reason for hiding this comment

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

I'm not sure this is the best place to do this. I'd like to hear the opinion of someone more familiar with this codebase.

Copy link
Member

Choose a reason for hiding this comment

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

can you give a more verbose name to rel_mgr please? also share a bit more of what this would be doing?

@felipediel felipediel marked this pull request as draft January 27, 2024 07:09
@felipediel
Copy link
Author

felipediel commented Jan 27, 2024

I just realized there's a side case here. The child may not be a ModelSerializer. I'll leave it as a draft while I think about it, suggestions are welcome.

We could create a new ModelListSerializer class with these changes and have it as the default list_serializer_class of ModelSerializer. @auvipy let me know what you think.

@auvipy auvipy self-requested a review January 29, 2024 13:35
Copy link
Member

@auvipy auvipy left a comment

Choose a reason for hiding this comment

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

I think we should have appropriate test cases for this before even trying to fix them

@felipediel
Copy link
Author

Agree, I'll do it

Copy link
Member

@auvipy auvipy left a comment

Choose a reason for hiding this comment

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

as you can see the CI builds are failing, can you please rebase and make it green at least? possibly with very basic test? you can try incremental approach to fix the problem

@felipediel
Copy link
Author

Yes, I will do it. Sorry for the delay, I'm struggling to find time to continue this PR, any help is welcome

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

Successfully merging this pull request may close these issues.

None yet

2 participants