Search code examples
djangodjango-database

What happens when a Django table hits max on an ID/PK column?


Lets imagine that you have an application where an specific table has A LOT new objects (in Django terms) created. Nevermind how many are deleted, but let's say it is sufficient to keep the table functional.

After quite a while, how unlikely it may ever be, the table hits max on the ID/PK column. What happens next? How does Django handle that situation?


Solution

  • I tried to set an id of 2147483648 with a Postgres database. Django raises DataError: integer out of range. If I try the same in Postgres I get [22003] ERROR: integer out of range. So it looks like Django just throws the db error.

    If I search the Django source code for DataError I find: https://github.com/django/django/blob/3c447b108ac70757001171f7a4791f493880bf5b/django/db/utils.py#L53 which confirms that Django re-throws backend-specific database exceptions.

    You can always define the primary key field yourself and mark it as primary:

     id = models.BigIntegerField(primary_key=True)
    

    This will increase id's form 2147483647 to 9223372036854775807.

    If that isn't enough switch to uuid:

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    

    https://docs.djangoproject.com/en/1.10/topics/db/models/#automatic-primary-key-fields and https://docs.djangoproject.com/en/1.10/ref/models/fields/#bigintegerfield and https://docs.djangoproject.com/en/1.10/ref/models/fields/#uuidfield