2

Is there a way to create an AutoField in Django that always begins with a certain prefix?

I would like to create an AutoField that always begin with the number 1, where the first 15 saved records would have the values 11, 12, 13, 14, ..., 19, 110, 111, 112, 113, 114, 115.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
touch my body
  • 1,634
  • 22
  • 36

1 Answers1

0

First of all, you can't create a second AutoField if one is already being used for the primary key because some database backends (such as MySQL) does not support it. See https://code.djangoproject.com/ticket/8576

Second, no, you can't do that but you can override save method to populate a second column that will concatenate 1 with your automatically generated id, i.e.:

class MyModel(models.Model):
    ...
    custom_id = models.IntegerField()

    def save(self, *args, **kwargs):
        if self.custom_id is None:
            self.custom_id = int('1' + str(self.id))
        return super(MyModel, self).save(*args, **kwargs)
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Thanks! It was never my intention to create a second `AutoField`, since that doesn't make sense. But thanks for the save override idea! – touch my body Jul 04 '18 at 02:15