Opened 4 years ago

Closed 4 years ago

#32838 closed Cleanup/optimization (wontfix)

Migrations create extra index when foreign key is also part of a unique constraint

Reported by: Lev Owned by: nobody
Component: Database layer (models, ORM) Version: 3.2
Severity: Normal Keywords: postgres, indexes, unique constraint, foreign keys
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Given a model like so:

class Person(models.Model):
    name = models.TextField()

class Address(models.Model):
    person = models.ForeignKey(Person, on_delete=models.PROTECT)
    street = models.TextField()

    class Meta:
       unique_together = ["person", "street"]

and a Postgres backend, Django will create two btree indexes, one on the foreign key "person" and another on "person, street" to enforce the unique constraint. In this case, the "person" index is redundant and wasteful since the "person, street" index is sufficient. We can check for the foreign key index being covered by the unique index and not create it if that's the case.

Change History (1)

comment:1 by Mariusz Felisiak, 4 years ago

Resolution: wontfix
Status: newclosed

Thanks for this ticket, however it is a documented behavior. It's also documented how to disable ForeignKey indexes if you want to avoid the overhead:

A database index is automatically created on the ForeignKey. You can disable this by setting db_index to False. You may want to avoid the overhead of an index if you are creating a foreign key for consistency rather than joins, or if you will be creating an alternative index like a partial or multiple column index.

There are also valid cases for a separate index (see comment). IMO we shouldn't break this.

You can raise the idea on the DevelopersMailingList to reach a wider audience and see what other think. We can re-open this ticket if we reach consensus on the mailing list.

Note: See TracTickets for help on using tickets.
Back to Top