Django Admin Sortable Model (move up and down)

I have a model, let’s say Post, that has an integer ordinality field. Post belongs to Category:

class Category(models.Model):
    name = models.CharField(max_length=128)

class Post(models.Model):
    name = models.CharField(max_length=128)
    ordinality = models.IntegerField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

In the admin panel, I want to:

  • Filter posts by category, don’t just show all posts
  • Order posts by ordinality
  • Be able to change the ordinality from the list view, by clicking “up” and “down” links in the table
  • Be smart when creating new Post models and automatically set the ordinality so that it’s last

Eg: If I have a Post(name="Post 1", ordinality=1, category=general) and I create a new one, ordinality should be set to 2. If there’s already a Post in the same category with ordinality 2, it should be 3, and so on. So the ordinality is scoped by category in this case.

I’m new to Django (coming form Rails) and I want to know “the Django way” to solve this. I’m not sure if this is doable with the admin (I don’t mind implementing my own admin extensions) or if I should create a custom page for this.

Thanks in advance :slight_smile:

When looking for ideas or modules to perform specific functions, one place to check is

In this case, try searching for “sort”. You should see django-admin-sortable2 as one of the top options.

It may be sufficient for what you need - it may not, but it should be a suitable starting point for further research.

Thanks! It is quite limited, but I managed to make it work using django-admin-sortable2 :slight_smile:

It does not work with order_with_respect_to, and it forces you to sort the list view, even if you only want to use it in the StackedInline, but I think that’s Django’s admin panel design.