Django packs every model with auto increment field id which works most time but there can be situations where you need additional fields.

auto_increment_id = models.AutoField(primary_key=True)

This does gives you an additional field that auto increments itself but

  • it starts count from o.
  • It doesn’t let you have custom value like an extension or a higher digit count.

In here I’ll show you how to get function that can get a custom unique ID for model, I made this when working on a ticketing platform for my business where I needed a unique ID with

  • an extension of my business name (RoomnHouse=>RNH).
  • Month and Year of Object create date.
  • A big ID :p

Solution is to make a new function that will look for created last ID and increments/processes a new ID.


import datetime
...
...
def increment_booking_number():
  last_booking = Booking.objects.all().order_by('id').last()
  if not last_booking:
    return 'RNH' + str(datetime.date.today().year) + str(datetime.date.today().month).zfill(2) + '0000'
  booking_id = last_booking.booking_id
  booking_int = int(booking_id[9:13])
  new_booking_int = booking_int + 1
  new_booking_id = 'RNH' + str(str(datetime.date.today().year)) + str(datetime.date.today().month).zfill(2) + str(new_booking_int).zfill(4)
  return new_booking_id

....
...
..
class Booking(models.Model):
 booking_id = models.CharField(max_length = 20, default = increment_booking_number, editable=False)

I am not resetting the last 4 digits on new date because my accounting team said they need a continuity in last digit , but you can have a new value for new month and year.

Note if you are installing this to a field in model that has objects, make sure to create the field with a default value then replace it with the function.

I’m sure this will reduce the performance, and this definitely is not a filed you should use inside your application other than for display needs. Since this was a temporary micro website I haven’t done much of work on analyzing the speed. If you do so let me know in comments.