Search code examples
pythondjangomodels

How do I get a default Value for a Field that usually increments in Django?


I'm writing a small piece of software for accounting. One function is to create bills. These bills have a serial number that is supposed to increment with every bill. But sometimes I need to create one outside of this system so I need to be able to change the value. So what I'm looking for is a way to have an integer field with a default value in Django admin that's always the max value + 1 but will be editable. Unfortunately I don't know where to start. How can I do this?


Solution

  • You can do it by using a function or lambda expression as the default:

    class Bill(models.Model):
        serial = models.IntegerField(default=lambda: Bill.objects.latest('id').serial + 1)
        # ...
    

    Basically, grab the latest model, and use its serial (plus one) as the default value. This will work if your serial is an integer, otherwise you'll have to use your own logic. Also note that .latest() will raise DoesNotExist if you don't have any bills in the database.