[Answered ]-Django update order field on save

1๐Ÿ‘

I guess you should to differentiate between insert and moving. You know is a move because your model pk is not none. On move, you only must change the order of books between the last place and new.

class Section(models.Model):
    name = models.CharField()
    order = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        is_insert = self.id is not None
        if is_insert:
          # is insert, reorder all
          existing_sections = (
            Section.objects.filter(
                order__gte=self.order
            )
            .exclude(id=self.id)
            .order_by("order")
          )
          existing_sections.update(order=F("order") + 1)
        else:
          # is moving a book
          previous_order = (
            Section
            .objects
            .filter(pk=self.id)
            .values_list('order', flat=true)
            [0])
          Section.objects.filter(
             order_gte=previous_order
          ).filter(
             order_lte=self.order
          ).exclude(id=self.id
          ).update(order=F("order") - 1)

        super(Section, self).save(*args, **kwargs)

Disclaimer: not tested, I just wrote here the code. Take the idea and debug the process

๐Ÿ‘คdani herrera

Leave a comment