Reputation: 41
I know Django auto generates a ID for my model with a primary_key
And I also know that if I want to generate a custom id I should do:
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
But how can I change this so the id would look like this YYYYMMDDXXXXXX
?
Where:
YYYY = year
MM = month
DD = day
XXXXXX = random number
Upvotes: 4
Views: 3658
Reputation: 9931
I don't see a reason why you should make a id like that but yeah you can do it. Just create a small function to generate id and pass it to your field.
import datetime
from uuid import uuid4
def create_id():
now = datetime.datetime.now()
return str(now.year)+str(now.month)+str(now.day)+str(uuid4())[:7]
Then in model field
id = models.CharField(primary_key=True, default=create_id, editable=False)
Remember to pass function object as parameter not a callable.
Upvotes: 2