alias51
alias51

Reputation: 8608

Does Django index Autofield / ID keys in PostgreSQL?

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?

Upvotes: 1

Views: 2041

Answers (1)

Alasdair
Alasdair

Reputation: 308839

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.

Upvotes: 5

Related Questions