5

I want to shard my database so I can't use foreign key constraints. I have following models

from django.db import models


class A(models.Model):
    b_one_to_one = models.OneToOneField(
        'B', on_delete=models.SET_NULL, db_constraint=False, null=True
    )

    b_one_to_many_null = models.ForeignKey(
        'B', on_delete=models.SET_NULL, db_constraint=False, null=True,
        related_name='+'
    )
    b_one_to_many_nothing = models.ForeignKey(
        'B', on_delete=models.DO_NOTHING, db_constraint=False,
        related_name='+'
    )


class B(models.Model):
    pass

python manage.py makemigrations command generates following sql code

BEGIN;
--
-- Create model A
--
CREATE TABLE `a` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY);
--
-- Create model B
--
CREATE TABLE `b` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY);
--
-- Add field b_one_to_many_nothing to a
--
ALTER TABLE `a` ADD COLUMN `b_one_to_many_nothing_id` integer NOT NULL;
--
-- Add field b_one_to_many_null to a
--
ALTER TABLE `a` ADD COLUMN `b_one_to_many_null_id` integer NULL;
--
-- Add field b_one_to_one to a
--
ALTER TABLE `a` ADD COLUMN `b_one_to_one_id` integer NULL UNIQUE;
CREATE INDEX `a_b_one_to_many_nothing_id_4fca4209` ON `a` (`b_one_to_many_nothing_id`);
CREATE INDEX `a_b_one_to_many_null_id_e498aa17` ON `a` (`b_one_to_many_null_id`);
COMMIT;

I understand that Django might want to create an index for b_one_to_many_null field due to on_delete=models.SET_NULL setting, but I don't understand why there is a need for an index for b_one_to_many_nothing field.

Is there a way to turn this automatic index creation off or it's just a Django bug?

I'm using Django 1.11.5.

1
  • 1
    Try db_index=False - based this docs Commented Oct 29, 2017 at 14:23

1 Answer 1

5

Thanks to @dahrens I reread Django documentation and it says

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.

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.