I've got an abstract base class from which many models inherit. It defines a field called order
. I've built this into the system because I often need to order my objects in arbitrary ways (for listing in template, for example). However, I often find that the order fields get away from me and I lose track (I'm allowing null=True
and blank=True
). I'd like to have a way to ensure that whenever an object of model type with order is created, Django looks to other objects of the same type and checks the highest order number and increments accordingly.
Is this possible? I've tried making the field order
auto increment (with AutoField
) but Django complains saying I've got an auto field already, the primary key. I'd use the primary key ID but this is assigned arbitrarily and doesn't maintain the order I want.
Here is the model factory that houses the model in question:
def abstract_base_model_factory():
class AbstractBaseModel(models.Model):
order = models.IntegerField(null=True, blank=True)
class Meta:
abstract = True
return AbstractBaseModel
Since I was mainly interested in this value in the Django Admin, I went with this method in the ModelAdmin
, using the information from this question and answer:
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
def increment_order(self):
obj = MyModel.objects.order_by('-order').first()
number = obj.order
return number + 1 if number else 0
def get_changeform_initial_data(self, request):
return {'order': self.increment_order}
The provided answer was helpful but had a few things incorrect about it, which is why I'm not selecting it as accepted. Thanks either way @weAreStarDust.