很顯然上面的AutoField字段不能使用,因為AutoField字段是IntegerField字段,所以不能將pk用來AE860000001,從目標字段來看,很顯然是字符串類型,所以只能將字段類型改為CharField。

ID自增
Django models里面ID自增通常使用models.AutoField(auto_created=True, primary_key=True)來定義主鍵,但是如何自定義ID自增怎么做呢?類似于在ID前面添加固定字符串如:AE8600000001、AE8600000002、AE8600000003……
案例分析
很顯然上面的AutoField字段不能使用,因為AutoField字段是IntegerField字段,所以不能將pk用來AE860000001,從目標字段來看,很顯然是字符串類型,所以只能將字段類型改為CharField,但是呢,如果數(shù)據(jù)量巨大,字符串作為主鍵顯然是不理智的選擇,這樣會嚴重影響到查詢性能問題,但是也不是不可使用。這樣必須重寫models里面的save方法,達到字段自增的目的(其實也可以用另外一張表記錄ID游標的方式也可,但是個人覺得比較麻煩,不知道有沒有大神知道更為簡便的方法)。
獲取最大值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)
弊端
重寫save方法固然好用,但是有一種創(chuàng)建數(shù)據(jù)的方式不行,那就是批量創(chuàng)建的方法不適用,因為它的底層不調(diào)用save方法,objects.bulk_create這個方法,咱們可以看一下底層源碼:
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
寫到這里,估計你們會產(chǎn)生疑問,這樣寫會不會出現(xiàn)問題,在生產(chǎn)環(huán)境能用嗎?如果多個用戶同時嘗試,那么他就會發(fā)生IntegrityError錯誤。你們可以試試……
自定義方法
上面的方法存在一定的弊端,如果咱們每次重寫save方法的時候去查詢一下目前表里面的數(shù)量,創(chuàng)建臨時字段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ā)法也會和上面一樣,如果多用戶使用,也會產(chǎn)生IntegrityError錯誤。啊啊啊,有沒有大神求教,目前只能這樣實現(xiàn)了。