1

Django's docs state that id fields created with AutoField are indexed:

id is indexed by the database and is guaranteed to be unique.

Similarly it applies an index to every FK relationship.

However, in PostgreSQL whilst FKs appear to be indexed, IDs are not. Here's an example:

class TestModelBase(models.Model):
    name = models.CharField(max_length=50)
    fkfield = models.ForeignKey(TestModelFK, blank=True, null=True,
                                on_delete=models.CASCADE)
    m2mfield = models.ManyToManyField(TestModelM2M, related_name='base_m2m')

This model appears to apply the fkfield index, but not the id autofield. From PGAdmin below:

enter image description here

Am I missing something?

1 Answer 1

5

PostgreSQL automatically creates indexes for primary keys. From the docs:

Adding a primary key will automatically create a unique B-tree index on the column or group of columns listed in the primary key, and will force the column(s) to be marked NOT NULL.

It appears that PGAdmin does not show those indexes. This mailing list thread is the best source I could find.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Interesting that django + postgres will still let you manually create an index on a primary key (e.g. indexes = [models.Index(fields=['id'], name='%(class)s_id_idx'),] ). I would have thought it would reject the duplicate?
Postgres allows multiple indexes on the same field so Django should as well. It might be useful if Django had a system check to warn about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.