Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

python - Django generate custom ID

I saw this answer but there is no specific answer yet. I want to create custom id that starts with letter. When a new record comes into database I want to change the id to A00001, .... A00002, .... A00010, ...A10000 etc. The id will be always in range 99999- 00001 so how can I do that?

my model is simple:

class Custom(models.Model):
    id = models.AutoField(primary_key=True, editable=False)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...