我想做一个自定义序列,例如:
如果它是数据库中的第一个对象,我将创建一个对象并将其命名为A001。
如果对象不断增加并达到A999,则名称将从B001开始。一旦达到B999,它将再次从C001开始。
答案 0 :(得分:2)
我会在这里为您提供一个覆盖save
方法的简单解决方案。
我们说我们有这个对象:
import string
class YourClass(models.Model):
alph_counter = models.CharField(max_length=4, blank=True, null=True, verbose_name=_(u'Alphabet Counter'))
def save(self, *args, **kwargs):
if self.__class__.objects.all().count() == 0:
# First object need to be set like this
letter = 'A'
number = 1
# %03d used to write the number with 2 zeros before
self.alphcounter = '%s%03d' (letter,number) # 'A001' this time
else:
# Get the last object ID
last_id = self.__class__.objects.all().order_by("-id")[0].id + 1
# We need to know wich letter is it, we use division over ID
wich_letter = (last_id+1) / 1000
letter = string.uppercasecase( wich_letter )
number = (last_id+1) % 1000
self.alphcounter = '%s%03d' (letter,number)
super(self.__class__, self).save(*args, **kwargs)