Customizing Incremental Primary Keys with Prefixes and Suffixes in Django
Recently, a requirement emerged in the project. In Django’s model, the primary key needed to be an incremental type with a prefix, like: exp-1, exp-2… and so on. Moreover, across all models, the incremental data within the primary key had to be unique, without any duplicates. That is, if there are two models A and B, once exp-1 is used in A, it is not allowed to be used in B. After searching online, I couldn’t find a particularly good implementation method, so I wrote one myself and am making a record here.
The method I adopted is actually quite simple:
- Create a separate model with only one field of the models.AutoField type, which can ensure that the incremental number in the primary key is globally unique.
- Define a primary key of the models.CharFiled type in the actual business model.
- Modify the save method to add a prefix to the primary key of the business model.
Here is the sample code for reference:
1 | from django.db import models |