The AutoField
field is a kind of IntegerField
field, so you can't use PKs as A00001
.
So, the possible way to achieve the requirement is to change the AutoField
to CharField
.
Technically you can use "String PK Field" But, you should be aware of the problems/performance issues if you are going to use that.
Here I found one nice SO post that explains the same - Strings as Primary Keys in SQL Database
========================================================================
If you still really wish to migrate to String PKs, read the following
First you need to use the CharField
instead of AutoField
and override the save()
method of model
from django.db.models import Max
class Custom(models.Model):
id = models.CharField(primary_key=True, editable=False, max_length=10)
name = models.CharField(max_length=100)
def save(self, **kwargs):
if not self.id:
max = Custom.objects.aggregate(id_max=Max('id'))['id_max']
self.id = "{}{:05d}".format('A', max if max is not None else 1)
super().save(*kwargs)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…