1

is there any possibility to define a Field which gets incremented, but starts with a letter? So the values should be like: S123, S124, S125.

I' d like to use the id field for it, but some reason i' d like to have it as a CharField.

As a workaround i could use:

id = models.CharField(max_length = 32, primary_key = True)

and redefine the save method, so i always precalculate its value, but this won' t be that robust than a "real" solution, and also my solution would too slow with the calculation.

Is there a proper solution for my problem?

Django: 1.9.2 Python: 3.4.2

.

user2194805
  • 1,201
  • 1
  • 17
  • 35
  • This might be of interest for you: https://docs.djangoproject.com/es/1.9/ref/models/fields/#django.db.models.UUIDField – crystalAhmet Dec 27 '16 at 14:59

1 Answers1

2

I don't think you should manually define a primary key. Django usually uses relational database to build an app, which means it would rely on some key field to join other tables to do the lookup when it needs to. Having primary keys like S123 makes it extra hard to maintain because you need to store the same thing as a reference in other tables.

What I would suggest is storing the letter part and the digits separately. You could use the default id field django created as the digit part and create your own field to store the letter part. Then you would use a property method to return the value you want to have. Roughly:

class Foo(models.Model):
    letter = models.CharField(max_length=1)

    @property
    def symbol(self):
        return '%s%s' % (self.letter, self.id)

Then you could do:

foo = Foo.objects.create(letter='S')
print foo.symbol   # this would print S1, S2, etc.

In case you don't know, here's an explanation of @property in python.

Community
  • 1
  • 1
Shang Wang
  • 24,909
  • 20
  • 73
  • 94
  • Well, as a final solution i added a new field (c_id, CharField), and i maintain its value during the post_save signal (when it' s created). – user2194805 Dec 29 '16 at 13:35