1

Consider a model Section that is displayed on a site and created / edited by a user using the Django admin interface. I would like to add a field that allows the user to easily control the order in which sections are displayed on the site. The easiest option seems to be to allow for an integer field that is auto-incremented but can be edited by the user -- akin to what the built-in AutoField does.

However, to make editing the order easier, I would like to increment the fields default value by 10 every time, to allow the user to shift sections around more easily. The first section would get order=1, the next one order=11 and so on, that way a section can be wedged in between those first two by giving it, e.g., order=6.

Is there a way I can reuse AutoField to achieve this purpose? And if no, how could I best achieve this type of ordering scheme?

Ideally, what I'd like to achieve should look like this:

from django.db import models

class Section(models.Model):
    text = models.TextField()
    order = AutoField(step=10)
    
    class Meta:
        ordering = ('order',)
Samuel
  • 18,286
  • 18
  • 52
  • 88

1 Answers1

0

Autofield won't work. Not editable, needs to be primary key.

I also suggest to solve this visually using drag and drop in the UI and then reorder all sections within the whole, rather then allow wedging. If two people at the same time wedge 25 within 20 and 30, you still have the same problem. Reordering on save is a much cleaner solution, especially when using select_for_update:

Returns a queryset that will lock rows until the end of the transaction, generating a SELECT ... FOR UPDATE SQL statement on supported databases.