ジャンゴ:Unique_togetherは、ForeignKeyと同じ方法でdb_index=Trueを意味しますか?

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

質問

モデル上のフィールド, foo = models.ForeignKey(Foo) ルックアップを高速化するために、列のデータベースインデックスを自動的に追加します。それは良いことですが、Djangoのドキュメントでは、model-metaのフィールドかどうかは記載されていません unique_together 同じ治療を受ける。私は偶然にリストされている1つのcharフィールドがあるモデルを持っています unique_together クイックルックアップのためのインデックスが必要です。私はそれが重複を追加するために何も傷つけないことを知っています db_index=True フィールド定義では、しかし、私は好奇心が強いです。

役に立ちましたか?

解決

unique_together リストに含まれる各フィールドのインデックスは自動的に追加されません。

Djangoの新しいバージョンでは、代わりにインデックスと制約メタオプションを使用することをお勧めします:

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

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

他のヒント

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.

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