我需要在这个Django模型上添加db_index吗?

25 投票
1 回答
5367 浏览
提问于 2025-04-16 10:50
class Comments(models.Model):
    content = models.ForeignKey(Content)

我需要给“content”加一个数据库索引吗?还是说因为它是外键,所以会自动被索引?

1 个回答

44

除非特别说明,否则会为ForeignKey创建一个索引。相关的源代码如下:

class ForeignKey(RelatedField, Field):
    # snip
    def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs):
        # snip
        if 'db_index' not in kwargs:
            kwargs['db_index'] = True

撰写回答