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:

  1. 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.
  2. Define a primary key of the models.CharFiled type in the actual business model.
  3. Modify the save method to add a prefix to the primary key of the business model.

Here is the sample code for reference:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from django.db import models


class AutoIncrementFields(models.Model):
"""
provide a unique ID for all models of code sign
"""
id = models.AutoField(primary_key=True)
def __str__(self):
return str(self.id)


class A(models.Model):
"""
example
"""
case_id = models.CharField(max_length=128, primary_key=True) # custom save func will cover this field

def save(self, *args, **kwargs):
"""
customize primary key like exp-1, exp-2...
:param args:
:param kwargs:
:return:
"""
_ = AutoIncrementFields.objects.create()
self.case_id = 'exp-' + str(_.id)
return super(A, self).save(*args, **kwargs)


class B(models.Model):
"""
example
"""
case_id = models.CharField(max_length=128, primary_key=True) # custom save func will cover this field

def save(self, *args, **kwargs):
"""
customize primary key like exp-1, exp-2...
:param args:
:param kwargs:
:return:
"""
_ = AutoIncrementFields.objects.create()
self.case_id = 'exp-' + str(_.id)
return super(B, self).save(*args, **kwargs)