Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Does unique_together imply db_index=True in the same way that ForeignKey does?

A field on a model, foo = models.ForeignKey(Foo) will automatically add a database index for the column, in order to make look-ups faster. That's good and well, but Django's docs don't state whether the fields in a model-meta's unique_together receive the same treatment. I happen to have a model in which one char field which is listed in unique_together requires an index for quick lookups. I know that it won't hurt anything to add a duplicate db_index=True in the field definition, but I'm curious.

like image 536
orokusaki Avatar asked Oct 20 '11 01:10

orokusaki


2 Answers

For anyone coming here wondering if they need an index_together in addition to unique_together to get the index's performance benefit, the answer for Postgres is no, they are functionally the same.

like image 200
Tom Avatar answered Sep 20 '22 00:09

Tom


If unique_together does add an index, it will be a multiple column index.

If you want one of the columns to be indexed individually, I believe you need to specify db_index=True in the field definition.

like image 43
Alasdair Avatar answered Sep 19 '22 00:09

Alasdair