Arundas R
Arundas R

Reputation: 770

Auto incrementing id value with string django

I am trying to create a model in which I have a case_id field. This field should be auto incrementing. But my case_id value should be in the format shown,

case_id=FAS150001 (This should be the first value)

class InformationRequest(models.Model):

    """Model to track information"""

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

How can I do this?

Upvotes: 2

Views: 981

Answers (1)

Zulu
Zulu

Reputation: 9285

Charfields cannot be auto-incremented.

But Django signals can help you to simulate this behavior. You could do a pre-save or post-save signal for make it, for example:

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()

Upvotes: 2

Related Questions