[Answered ]-Incremented CharField

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.

Leave a comment