[Django]-What's the reason why Django has SmallIntegerField?

45👍

Performance on many RDBMs can be heavily dependent on row size. While a "purist" approach might say that the application should be completely independent of the underlying data structure, over many rows improvements like using a smaller integer could shave gigabytes off table size, which makes more of the table fit in memory, which drastically improves performance.

I would use a small integer like this for say, a primary key on a table that would always have <100 rows, especially when this is stored as a foreign key in a table I expect to grow very large. While the size is implementation defined, it’s safe to assume that it is greater than 127 at the very least.

18👍

The field is database dependent, doesn’t that make it totally unreliable to use?

It’s not totally unreliable. SMALLINT is part of the SQL standard and certainly MySQL and PostgreSQL both have small integer types that go from -32768 to +32767

11👍

This is one of those things that is the way it is because it got that way.

Django supports SmallIntegerField because Django grew up on PostgreSQL, and PostgreSQL supports smallint. The PosgreSQL docs say

The smallint type is generally only used if disk space is at a premium.

While it seems kind of quaint now, when 1TB disks can be had at the corner store, it wasn’t all that long ago when disks were a lot smaller, costing significantly more per byte. Memory, too. Using a smallint (where appropriate) in an index means fitting more row indexes into RAM cache, which meant better performance.

3👍

You would choose SmallIntegerField if you wanted to save space in the database. The limit on the value is database-dependent, but that doesn’t make it unreliable. It just means you have to know what database system you are using, and find out what the limit is for that system.

-3👍

Year is date without taking care of months and days. Choose the DateField and hence enjoy all the power Django provides to you. Since you store born yeas, this also allows you in the future to simply accept months and days.

Leave a comment