0

I have the following model in django:

class Page(models.Model):
    page_number = models.IntegerField()
    ...

and I would like to make sure that this page number keeps being a sequence of integers without gaps, even if I delete some pages in the middle of the existing pages in the data base. For example, I have pages 1, 2 and 3, delete page 2, and ensure page 3 becomes page 2.

At the moment, I am not updating the page_number, but rather reconstructing an increasing sequence without gaps in my front end by:

  • querying the pages
  • sorting them according to page_number
  • assigning a new page_order which is incremental and without gaps

But this does not seem to the be best way to go...

Greg
  • 3
  • 1
  • How are you deleting the pages?- is it through the admin pages or do you have a view? – Nealium Oct 20 '22 at 17:11
  • Right now it's through the admin, I am developping a survey app. But in the future there should be custom views to manage the survey design (associated to some backend management app). – Greg Oct 20 '22 at 17:35

1 Answers1

0

Basically you'd have to manually bump all of the pages down

When you get to custom views you'd do something like this:

def deletePage(request):
    if request.method = 'POST':
        pageObj = Page.objects.filter(page_number=request.POST.get('page_number')).first()
        if pageObj:
            pageObj.delete()

            # Note: Using F() means Django doesn't need to Fetch the value from the db before subtracting
            #   - It's a blind change, it's faster though
            from django.db.models import F
            for i in Page.objects.filter(page_number__gt=request.POST.get('page_number')):
                i.page_number = F('page_number') - 1
                i.save()

        else:
            # No Page Object Found
            # Raise some error
            pass

The admin page is tougher tho, you'd basically do the same thing but in functions described in: Django admin: override delete method

  • Note: Deleting multiple would be tough, especially if you're deleting page 2 + 4 + 5. Possible, but a lot of thinking involved
Nealium
  • 2,025
  • 1
  • 7
  • 9