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

SortableModel save method improvement #15559

Open
Adilkhanweb opened this issue Mar 7, 2024 · 0 comments
Open

SortableModel save method improvement #15559

Adilkhanweb opened this issue Mar 7, 2024 · 0 comments

Comments

@Adilkhanweb
Copy link

Adilkhanweb commented Mar 7, 2024

Current code

    @staticmethod
    def get_max_sort_order(qs):
        existing_max = qs.aggregate(Max("sort_order"))
        existing_max = existing_max.get("sort_order__max")
        return existing_max

    def save(self, *args, **kwargs):
        if self.pk is None:
            qs = self.get_ordering_queryset()
            existing_max = self.get_max_sort_order(qs)
            self.sort_order = 0 if existing_max is None else existing_max + 1
        super().save(*args, **kwargs)

Improved code

    def save(self, *args, **kwargs):
        if self._state.adding:
            existing_max = self.__class__.objects.aggregate(Max('sort_order'))
            existing_max = existing_max['sort_order__max']
            self.order = 0 if existing_max is None else existing_max + 1
        super().save(*args, **kwargs)
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