如何在 django 中创建自定义 ID?

sod*_*mzs 2 django django-templates django-models django-forms django-views

据我所知,我们可以使用 UUIDField() 创建自定义 ID。

\n

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

\n

但我怎样才能改变看起来像这样的ID AAYYMMDDNNNN

\n

在哪里,

\n

\xe2\xa6\x81 前 2 个字符 - 'AA'

\n

\xe2\xa6\x81 YY - 捕获其注册年份

\n

\xe2\xa6\x81 MM - 捕获其注册的月份

\n

\xe2\xa6\x81 DD - 捕获其注册的当前日期

\n

\xe2\xa6\x81 NNNN - 将生成基于每天新的 NNNN 组的随机数 (0001 - 9999)

\n

rud*_*dra 6

你可以这样尝试:

import random
from django.utils import timezone

def generate_pk():
    number = random.randint(1000, 9999)
    return 'AA{}{}'.format(timezone.now().strftime('%y%m%d'), number)

class YourModel(models.Model):
   id = models.CharField(default=generate_pk, primary_key=True, max_length=255, unique=True)
Run Code Online (Sandbox Code Playgroud)

更新

根据评论更新,因为您想跟踪今天是否创建了任何实例并增加NNNN的计数器,您不能使用函数来生成默认值。相反,尝试重写 save 方法,如下所示:

import random
from django.utils import timezone

class YourModel(models.Model):
   special_id = models.CharField(max_length=255, null=True, default=None)

   def save(self,*args, **kwargs):
       if not self.special_id:
           prefix = 'AA{}'.format(timezone.now().strftime('%y%m%d')
           prev_instances = self.__class__.objects.filter(special_id__contains=prefix))
           if prev_instances.exists():
              last_instance_id = prev_instances.last().special_id[-4:]
              self.special_id = prefix+'{0:04d}'.format(int(last_instance_id)+1)
           else:
               self.special_id = prefix+'{0:04d}'.format(1)
       super(YourModel, self).save(*args, **kwargs)
        
Run Code Online (Sandbox Code Playgroud)