我写了这个:
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)
但我并不为此感到自豪。有一个更好的方法吗?我可以将它滚动到一个字段中,但不确定如果我在那里重构代码,我将如何返回模型表。我不能使用自动增量列,因为作为 FK 值,这些值无法更改。