使用字符串 django 自动递增 id 值

Auto incrementing id value with string django

我正在尝试创建一个模型,其中有一个 case_id 字段。该字段应自动递增。但是我的 case_id 值应该是显示的格式,

case_id=FAS150001(这应该是第一个值)

class InformationRequest(models.Model):

    """Model to track information"""

    case_id = models.CharField(max_length=50)
    user = models.ForeignKey(User)
    information = models.TextField()

我该怎么做?

字符字段不能自动递增。

但是Django signals可以帮助您模拟这种行为。你可以做一个预保存或 post-保存信号来制作它,例如:

from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import InformationRequest


@receiver(pre_save, sender=InformationRequest)
def my_handler(sender, instance=None, **kwargs):
    # Compute case_id, ex:
    # instance.case_id = increment_case_id()