I have a specific requirement for a Django model field, essentially I want to create this type of series:
0025-0007
Essentially 4 integer fields, one character, and 4 integer fields thereafter, I don’t need an auto-increment as the number changes, is there anything available in Django already that handles such fields, ideally something with automatic validation?
>Solution :
You can define a validator and work with a CharField and a RegexValidator [Django-doc]:
from django.db import models
from django.core.validators import RegexValidator
class MyModel(models.Model):
my_field = models.CharField(
max_length=9,
validators=[RegexValidator(r'\d{4}.\d{4}', 'The value should be four digits, a character and four digits')]
)
If the separator between the four digits is always a hyphen, you use r'\d{4}-\d{4}' instead.