Custom Auto Increment Field in Django

Create a custom auto incrementing field in django mode.

Advert

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.

Comments

Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Ad

Last 5 Articles

All Articles >

  1. How to Remove an App from Django Project

     
  2. Parse Time HH:mm:ss without date in javascript

     
  3. Software Testing

     
  4. Best WordPress Themes For Photographers And Photography

     
  5. Problems That Affect Conversion Rates

     

News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.