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 帖子,解释了相同的内容 - Strings as Primary Keys in 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屋!