I am developing an app in Django.
I want to insert in my model an auto-incrementing alphanumerical ID field, having, by default, a fixed alphabetical part and an auto-incrementing numerical part.
But I also want the availability to change, from admin section, this id to another alphanumerical one, with a different alphanumerical and numerical part.
Please note: I don't want to overwrite the django default id field, I just want to include in my model a field that gets as default value an auto-incrementing alphanumerical value.
Example of what I want:
Desired alphabetical constant part: ITM
Desired numerical auto-incrementing part: 00000
So that every object of my model, when generated, get default progressive values like: ITM00001, ITM00002, ITM00003, ...
Also, I would like to be able to change the field value from my admin section into values like ABC0000001, DFG0051, RST034, ...
Max field length: 10 (It can be also higher)
I realize that I have to use AutoField
and to somehow join the constant string with the auto-incrementing numerical variable, but I don't know how to do it.
class my_model(models.Model):
Field_1 = models.CharField(max_length=10, blank=True, null=True)
static_ID = models.AutoField(???)
What code should I write to get a field with the features I described upwards?
SOLVED:
Since I don't need a specific length for my id, nor a constant increment between two consecutive ids, I can use time.time()
to get a unique time number every time the object in the model is created. Then I can turn that time number into a string and concatenate it with a constant prefix.
In models.py:
import time
def return_timestamped_id():
prefix = "ITCH"
timestamp = str(int(time.time()*10000000))
default_value = prefix + timestamp
return(default_value)
class my_model(models.Model):
Field_1 = models.CharField(max_length=256)
static_ID = models.CharField(max_length=256, blank=False, null=False, default=return_timestamped_id)