很顯然上面的AutoField字段不能使用,因?yàn)锳utoField字段是IntegerField字段,所以不能將pk用來(lái)AE860000001,從目標(biāo)字段來(lái)看,很顯然是字符串類型,所以只能將字段類型改為CharField。

ID自增
Django models里面ID自增通常使用models.AutoField(auto_created=True, primary_key=True)來(lái)定義主鍵,但是如何自定義ID自增怎么做呢?類似于在ID前面添加固定字符串如:AE8600000001、AE8600000002、AE8600000003……
案例分析
很顯然上面的AutoField字段不能使用,因?yàn)锳utoField字段是IntegerField字段,所以不能將pk用來(lái)AE860000001,從目標(biāo)字段來(lái)看,很顯然是字符串類型,所以只能將字段類型改為CharField,但是呢,如果數(shù)據(jù)量巨大,字符串作為主鍵顯然是不理智的選擇,這樣會(huì)嚴(yán)重影響到查詢性能問(wèn)題,但是也不是不可使用。這樣必須重寫(xiě)models里面的save方法,達(dá)到字段自增的目的(其實(shí)也可以用另外一張表記錄ID游標(biāo)的方式也可,但是個(gè)人覺(jué)得比較麻煩,不知道有沒(méi)有大神知道更為簡(jiǎn)便的方法)。
獲取最大值ID
class TestNew(models.Model):
sequence_ID = models.CharField(primary_key=True, editable=False, max_length=50)
def save(self, *args, **kwargs):
if not self.sequence_ID:
max_id = TestNew.objects.aggregate(id_max=Max('sequence_ID'))['id_max']
self.sequence_ID = "{}{:08d}".format("AE86", max_id + 1 if max_id is not None else 1)
super().save(*args, **kwargs)
弊端
重寫(xiě)save方法固然好用,但是有一種創(chuàng)建數(shù)據(jù)的方式不行,那就是批量創(chuàng)建的方法不適用,因?yàn)樗牡讓硬徽{(diào)用save方法,objects.bulk_create這個(gè)方法,咱們可以看一下底層源碼:
def bulk_create(self, objs, batch_size=None):
"""
Inserts each of the instances into the database. This does *not* call
save() on each of the instances, does not send any pre/post save
signals, and does not set the primary key attribute if it is an
autoincrement field (except if features.can_return_ids_from_bulk_insert=True).
Multi-table models are not supported.
"""pass
寫(xiě)到這里,估計(jì)你們會(huì)產(chǎn)生疑問(wèn),這樣寫(xiě)會(huì)不會(huì)出現(xiàn)問(wèn)題,在生產(chǎn)環(huán)境能用嗎?如果多個(gè)用戶同時(shí)嘗試,那么他就會(huì)發(fā)生IntegrityError錯(cuò)誤。你們可以試試……
自定義方法
上面的方法存在一定的弊端,如果咱們每次重寫(xiě)save方法的時(shí)候去查詢一下目前表里面的數(shù)量,創(chuàng)建臨時(shí)字段ID,在此基礎(chǔ)上加1是否可行?
class TestNew(models.Model):
def ids():
c_no = TestNew.objects.count()
if c_no == None:
return 1
else:
return c_no + 1
emp_id = models.IntegerField(('Code'), default=ids, unique=True, editable=False)
sequence_ID = models.CharField(primary_key=True, editable=False, max_length=50)
def save(self, *args, **kwargs):
if not self.sequence_ID:
self.sequence_ID = "{}{:08d}".format("AE86", self.emp_id))
super().save(*args, **kwargs)
這種發(fā)法也會(huì)和上面一樣,如果多用戶使用,也會(huì)產(chǎn)生IntegrityError錯(cuò)誤。啊啊啊,有沒(méi)有大神求教,目前只能這樣實(shí)現(xiàn)了。