Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the best way to define a particular number with special characters in a database django

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading