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

4👍

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.

1👍

You can always use an AutoField for this. As that link shows, the database will automatically increment it for you, but you can still set your own explicitly.

See the section a few lines down that’s called Explicitly specifying auto-primary-key values.

👤Ben

Leave a comment