1

I have this special case, where a customer requires a specific (legacy) format of booking numbers, the first one starts with the current year: 2015-12345 So basically every year I would have to start from 0

The other one is starting with a foreign-key: 7-123 So the first document created by every the user gets number 1, and so on.

Unfortunately there will be long lists starting with this booking number, so fetching all the records and calculating the booking number is not really an option. I have also thought about overriding the save() method, reading and auto-incrementing manually, but what about simultaneous inserts?

WhatIsName
  • 2,294
  • 4
  • 24
  • 36
  • I posted a similar question [here](https://stackoverflow.com/questions/31594386/auto-create-alpha-numeric-id-for-django-model) to no avail. My team is looking to do this with SQL. – Malonge Aug 19 '15 at 17:19
  • @Malonge i have tried to answer the linked question. – e4c5 Aug 20 '15 at 01:56

1 Answers1

1

The best and most reliable way to do this is with a sql trigger That would completely eliminate the worries about simultaneous inserts. But overriding the save method is also perfectly workable.

Explicitly declare a primary key field and choose integer for it. In your save method if the primary key is None that means you are saving a new record, query the database to determine what should be the new primary key, asign it and save. Wherever you call your save method you would need to have a atomic transaction and retry the save if it fails.

BTW, you are starting for 0 each year. That's obviously going to be leading to conflicts. So you will have to prefix your primary key with the year and strip it out at the time you display it. (believe me you don't want to mess with composite primary keys in django)

e4c5
  • 52,766
  • 11
  • 101
  • 134
  • A comment on this question links to a similar issue. Alternatively you could try the approach I have just given as an answer to that question. https://stackoverflow.com/a/32108371/267540 – e4c5 Aug 20 '15 at 12:23