2

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.

karthikr
  • 97,368
  • 26
  • 197
  • 188
boatcoder
  • 17,525
  • 18
  • 114
  • 178
  • Check out this post: http://stackoverflow.com/questions/883575/custom-ordering-in-django It could help you – karthikr Mar 06 '13 at 18:16
  • @Carl Meyer's answer on that one points to this kind of field, just doesn't elaborate on a better way to come up with the sort_order. – boatcoder Mar 06 '13 at 21:06

2 Answers2

1

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.

boatcoder
  • 17,525
  • 18
  • 114
  • 178
0

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.

Aidan Ewen
  • 13,049
  • 8
  • 63
  • 88
  • Per the code: "A model can't have more than one AutoField." So, if you have an id field, you can't have a sort_order field. I suppose you could let the sort_order be the primary key, but that would cause all sorts of strange behaviors if you were deleting by an ID that could change. – boatcoder Mar 06 '13 at 21:03
  • Sorry, my bad, I should have checked up on it before posting my answer. I found more info about the implementation of multiple Auto fields here - https://code.djangoproject.com/ticket/8576 – Aidan Ewen Mar 06 '13 at 22:33