5

In my django model, when creating indexes via db_index=True in field definitions, the index is not created. Only if I created in the class Meta

class Agreement(UUIDPrimaryKey):
  job = models.ForeignKey(           
    'posts.Job',                   
    on_delete=models.CASCADE,      
    verbose_name=_("job"),         
  )
  class Meta:
    indexes = (
      models.Index(fields=['job']),
    )

And if I run makemigrations, the index is created.

Create index agreements__job_id_eb7df0_idx on field(s) job of model agreement

But If I change my model to:

class Agreement(UUIDPrimaryKey):
  job = models.ForeignKey(           
    'posts.Job',                   
    on_delete=models.CASCADE,      
    verbose_name=_("job"),
    db_index=True,
  )

And I run makemigrations, the index is deleted.

 Remove index agreements__job_id_eb7df0_idx from agreement

Should not be the same both definitions?

UPDATE

Documentation says they are the same. Yes both create index.. but if you create indexes in Meta, and do not specify db_index=False in the field definition, two indexes are created.

This is before setting db_index=False in the field

psql# select indexname from pg_indexes where tablename like 'agreemen%';

                 indexname                  
--------------------------------------------
 agreements__job_id_eb7df0_idx
 agreements_agreement_job_id_id_c26bd828
 agreements_agreement_pkey

And after setting db_index=False and running migrations/migrate

           indexname           
-------------------------------
 agreements__job_id_eb7df0_idx
 agreements_agreement_pkey

1 Answer 1

7

A database index is automatically created on the ForeignKey. At least so says the documentation: https://docs.djangoproject.com/en/2.1/ref/models/fields/#foreignkey. So it is not necessary to set db_index=True in your ForeignKey field of your model. The option is still there incase you don't want an index (db_index=False).

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

Comments

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.