boatcoder
boatcoder

Reputation: 18117

How to get an auto-incrementing sort order in a Django model

I wrote this:

class Department(models.Model):
    ...
    sort_order = models.IntegerField(help_text="Leave negative to place at end", default=-1)

    def save(self, *args, **kwargs):
        """ Set the sort order (if unset) to larger than the largest value"""
        if self.sort_order <= 0:
            largest = Department.objects.all().aggregate(x = models.Max('sort_order'))['x'] or 0
            self.sort_order = largest + 10
        super(Department, self).save(*args, **kwargs)

but I'm not proud of it. Is there a better way to do this? I could possibly roll this into a field, but not sure how I'd get back to the model table if I refactored the code there. I can't use the autoincrement column because as FK values, those can't be changed.

Upvotes: 3

Views: 1764

Answers (2)

boatcoder
boatcoder

Reputation: 18117

It appears that PositionField from Django Positions does this and is currently in use with Django CrowdSourcing. It's not exactly what I asked for, but appears that it might be a good, usable solution.

Upvotes: 1

Aidan Ewen
Aidan Ewen

Reputation: 13328

Sorry if I'm being obtuse, but doesn't django's built in AutoField do what you're looking for.

I know you don't want to mess with the primary key, but you could create another AutoField.

sort_field = models.AutoField()

Maybe you could look at overriding the AutoField to do what you want.

Upvotes: 0

Related Questions