【问题标题】:Django models: are there reasons to make searched field with db_index?Django 模型:是否有理由使用 db_index 进行搜索字段?
【发布时间】:2012-01-22 05:47:02
【问题描述】:

假设有表UserProfile:

class UserProfile(models.Model):
    name = models.CharField(max_length=30, db_index=True)     # db_index 1
    email = models.EmailField(unique=True, db_index=True)     # db_index 2
    password = models.CharField(max_length=60)
    birthday = models.DateField(db_index=True)                # db_index 3
    about = models.TextField(blank=True)
    created = models.DateField(auto_now_add=True)
    lang = models.CharField(max_length=1, choices=LANG, blank=True)

在网站上有带有过滤器的搜索表单:姓名、年龄、电子邮件。

那么,在这些过滤器中使用 db_index 真的有理由吗?

谢谢!

【问题讨论】:

    标签: django django-models django-database


    【解决方案1】:

    是的,当然。 Django 使用数据库,因此如果您在这些字段上进行搜索,查找将受益于数据库索引。

    请注意,一旦您创建了表,syncdb 将不会添加索引,即使您在将 db_index 添加到定义后再次运行它 - 您需要直接在数据库 shell 中修改表定义,或使用 South 这样的工具。

    请记住,与大多数规模问题一样,这些问题仅适用于您拥有大量统计数据的行(10,000 行不算大)。

    此外,每次插入时,都需要更新索引。所以要小心你添加索引的列。

    【讨论】:

    • 在 Django 1.5 之前,当您只能对单个字段进行索引时,当您执行 qs.filter(field1=foo, field2=2) 时的行为是什么,假设您已经对两个字段进行了索引。使用的索引?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2015-08-12
    • 2011-07-29
    • 1970-01-01
    • 2018-03-23
    • 2020-11-02
    • 2021-06-07
    相关资源
    最近更新 更多