Django: Подразумевает ли unique_topting db_index= True так же, как и ForeignKey?

StackOverflow https://stackoverflow.com/questions/7830091

Вопрос

Поле в модели, foo = models.ForeignKey(Foo), автоматически добавит индекс базы данных для столбца, чтобы ускорить поиск.Это хорошо и хорошо, но в документации Django не указано, получают ли поля в кодовом коде модели-меты такую же обработку.У меня есть модель, в которой одно поле char, указанное в unique_together, требует индекса для быстрого поиска.Я знаю, что добавление повторяющегося кода unique_together в определение поля ничему не повредит, но мне любопытно.

Это было полезно?

Решение

unique_together не добавляет автоматически индексы для каждого поля, включенного в список.

Новые версии Django предлагают вместо этого использовать мета-параметры индекса и ограничения:

https://docs.djangoproject.com/ru / 2.2 / ref / models / options / # unique-together

https://docs.djangoproject.com/ru / 2.2 / ref / models / options / # index-together

Другие советы

Для тех, кто приезжает сюда и задается вопросом, нужен ли им index_together в дополнение к unique_together для повышения производительности индекса, ответ для Postgres: нет , это функционально то же самое.

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.

In Django 1.5 and higher, you can use the {Model}.Meta.index_together class attribute. If you had two fields named foo and bar, you would add:

class Meta(object):
    index_together = unique_together = [
        ['foo', 'bar']
    ]

If you have only one set of unique fields, you can use a one-dimensional iterable for unique_together. However, the documentation does not indicate that the same applies to index_together.

This would also be okay:

class Meta(object):
    unique_together = 'foo', 'bar'
    index_together = [
        ['foo', 'bar']
    ]

This, however, is NOT supported by the documentation:

class Meta(object):
    unique_together = 'foo', 'bar'
    index_together = 'foo', 'bar'

According to the docs, it will only enforce uniqueness on database level. I think generally making a field unique does not imply it has an index. Though you could also simply check on db level if the index exists. Everything indicates though it does not.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top