Search code examples
pythondjangoautofield

Django add prefix to AutoField


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.


Solution

  • 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)