Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django AUTO INCREMENT for PK

I have some models in my Django app and I saw the field ‘auto_increment_id’ (as PK) doesn’t work as ‘AUTO INCREMENT’ (the DB is Postgres).

I made 2 records with auto_increment_id 1 and 2, delete record 2 and make a new one with auto_increment_id=3 instead of auto_increment_id=2.

models.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Testme(models.Model):
    auto_increment_id = models.AutoField(primary_key=True)
    year = models.ForeignKey(
        Year,
        verbose_name="Year",
        blank=False,
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return str(self.auto_increment_id)

enter image description here

How can I fix it?

Thanks a lot!

>Solution :

There’s nothing to fix. Postgres uses a counter for this – it doesn’t take "the first free space" in the id range, it just uses the next value of the counter.

It’s only there to be a unique value, so having gaps in the range where you’ve deleted records is not an issue.

(Also, no need to add this yourself – if you don’t specify primary_key=True on any field, Django will automatically add an id field that does this).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading