将 max_length 设置为非常大的值会消耗额外的 space 吗?

do setting the max_length to a very large value consume extra space?

我在模型中有一个字段,

name = models.CharField(max_length=2000)

输入的数据是,

name='abc'

django 模型的 max_length 设置为 2000 而输入的数据只有长度 3, max_length 是否为每个对象在数据库 table 中为 2000 个字符保留 space?保存模型对象后,space 是否被释放?

如果数据库中的对象数是几千或几百万,是否设置更高max_length会增加数据库的大小?

数据库是 postgres

CharField 在 PostgreSQL 中将由 character varying(max_length) 表示。

来自docs

The storage requirement for a short string (up to 126 bytes) is 1 byte plus the actual string, which includes the space padding in the case of character. Longer strings have 4 bytes of overhead instead of 1.

所以,字符串占用的磁盘 space 取决于它的长度 + 一个小的开销,而不是字段的最大长度。

使用更高的 max_length 不会增加数据库使用的磁盘 space。