Django模型字段索引 [英] Django Model Fields Indexing

查看:296
本文介绍了Django模型字段索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只知道索引是有用的,而且查询速度更快。

I only know that indexing is helpful and it queries faster.

后面的两个有什么区别?

What is the difference between following two?

1. class Meta:
       indexes = [
           models.Index(fields=['last_name', 'first_name',]),
           models.Index(fields=['-date_of_birth',]),
]

2. class Meta:
       indexes = [
            models.Index(fields=['first_name',]),
            models.Index(fields=['last_name',]),
            models.Index(fields=['-date_of_birth',]),
]


推荐答案

示例1:

第一个示例在 last_name first_name 字段上创建一个索引。

The first example creates a single index on the last_name and first_name field.

indexes = [
   models.Index(fields=['last_name', 'first_name',]),
]

如果您一起搜索姓氏和名字,或者单独搜索姓氏,这将很有用(因为 last_name 是索引中的第一个字段)。

It will be useful if you search on the last name and first name together, or the last name by itself (because last_name is the first field in the index).

MyModel.objects.filter(last_name=last_name, first_name=first_name)
MyModel.objects.filter(last_name=last_name)

但是,对于搜索 first_name 本身(因为 first_name 不是索引中的第一个字段)。

However, it will not be useful for searching for the first_name by itself (because first_name is not the first field in the index).

MyModel.objects.filter(first_name=first_name)  # not useful

示例2:

第二个示例为 first_name 字段和 last_name 字段的单独索引。

The second example creates an index for the first_name field and a separate index for the last_name field.

indexes = [
    models.Index(fields=['first_name',]),
    models.Index(fields=['last_name',]),
]

如果您根据代码中的名字或姓氏进行查找,则很有用

It will be useful if you do lookups based on first name or last name in your code

MyModel.objects.filter(first_name=search)
MyModel.objects.filter(last_name=search)

这篇关于Django模型字段索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆