How to use sequences

In addition to my primary key (‘id’) i would like to have a additional and uniqe (‘id_numeric’) field which is populated by independently the values of a postgresql sequence.

How can define this and how can i create a suitable migration if the ‘id_numeric’ field is added in subsequence and in addition to the primary key?

My django model looks like this:

class DesiredTenant(models.Model):
    _DEFAULT_MINIMUM_PASSWORD_LENGTH: int = 8

    class Meta:
        verbose_name = "Tenant"
        ]

    id = models.CharField("System-ID", primary_key=True, max_length=63, unique=True,
                          validators=[ALLOWED_CHARACTERS_REGEX_VALIDATOR],
                          help_text=f"The system id")

    id_numeric = models.PositiveIntegerField("Numeric-System-ID", editable=False,
                                             unique=True, null=False, blank=False)

Django does not support multiple auto increment fields in a model because not all of the backends allow it. (See #8576 (Multiple AutoFields in a model) – Django). You might be able to get something to work by creating the sequence and column assignment in PostgreSQL through a raw SQL statement, but I don’t know what that’s going to end up looking like in Django.

(As a side note, from a data modeling perspective, the desire to do something like that is generally regarded as having a “bad code smell”. I’d take a hard look at why you think this is necessary and whether it is truly necessary.)

1 Like