0

Just like how Django models automatically create an integer ID for each column entry of a database table, I would like it to automaticallty create an alpha numeric ID as well.

The integer can increment, while the character should be cycle through A-Z.

1_A
2_B
3_C
.
.
.
27_A
28_B

And so on.

Here is my models.py

from django.db import models
class Sample(models.Model):
    sample_ID = models.CharField(max_length=20) # Alpha numeric ID described above.
    sample_name = models.CharField(max_length=30)

As you can tell, this will produce a blank text field for users to enter this value in, though I would like it to be auto generated just as with the integer id. This will then be a fixed ID.

What confuses me about this is that I don't know how to incorporate customized/automated fields into a model (I am quite new to Django). Is there already a field that can do this? Or how can I make a custom field?

Django = 1.8

python = 2.7

Thank you

Malonge
  • 1,980
  • 5
  • 23
  • 33
  • Can this ID change over time? If not you might want to consider overriding `save` to create the value then. – shuttle87 Jul 23 '15 at 17:37
  • That is a good question. First of all, it must be unique for all samples. Accordingly, it might be best that once the user submits that sample, that they can't change the ID. That makes me think that maybe the user shouldn't be able to customize it. I will adjust the question. – Malonge Jul 23 '15 at 17:40
  • I don't know how to create such field on top of my head, but sounds like you can always use django default id and use `sample_ID` as the reference when you need it, right? You can then use whatever method you like to initialize it according your rule. – Shang Wang Jul 23 '15 at 18:54
  • Possible duplicate of [How to replace Django's primary key with a different integer that is unique for that table](http://stackoverflow.com/questions/37558821/how-to-replace-djangos-primary-key-with-a-different-integer-that-is-unique-for) – e4c5 Jul 20 '16 at 00:42

0 Answers0