chem1st
chem1st

Reputation: 1634

A Model field for integers with dashes in Django

I need a field for special identificator, to be more specific - CAS number, so the field should pass only integers and dashes. Is there a better way to hold such "dash-separated integers" than to use a CharField? Thanx.

Upvotes: 1

Views: 905

Answers (2)

GwynBleidD
GwynBleidD

Reputation: 20539

You can create your own django field, that will translate CAS number from one format to another. CAS is only at most 10 digits long, where last digit is checksum, so you can skip it when saving into database and calculate it on retrieving.

So even with 10 digits it will fit into integer field. Only work to do here is write django field that will translate format from one to another.

Upvotes: 0

awesoon
awesoon

Reputation: 33651

One of possible solutions is to use RegexValidator:

cas = models.CharField(max_length=11, validators=[RegexValidator(r'^\d\d-\d\d-\d\d-\d\d$')])

Upvotes: 4

Related Questions