Django生成自定义ID [英] Django generate custom ID
问题描述
我看到了此答案,但尚无具体答案。我想创建以字母开头的自定义 id
。当新记录进入数据库时,我想将 id
更改为A00001,.... A00002,.... A00010,... A10000等。 id
始终在 99999-00001
范围内,那我该怎么做?
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?
我的模型很简单:
class Custom(models.Model):
id = models.AutoField(primary_key=True, editable=False)
推荐答案
AutoField
字段是 IntegerField
字段,因此您不能将PK用作 A00001
。
所以,达到要求的可能方法是将 AutoField
更改为 CharField
。
从技术上讲,您可以使用字符串PK字段 但是,如果您是
在这里,我找到了一篇很好的SO帖子,解释了相同的内容-在SQL数据库中作为主键的字符串
===================== ======================================= ============
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
========================================================================
如果您仍然希望迁移到字符串PK ,请阅读以下内容
首先,您需要使用 CharField
而不是 AutoField
并覆盖模型的 save()
方法
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)
这篇关于Django生成自定义ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!