[Django]-Int vs String for field choices

6๐Ÿ‘

โœ…

I often see people using ints to do this.
Could someone explain why?

People use Small Integers (SmallIntegerField) because they are a much faster lookup than strings are in terms of retrieving values from a database. Much in the same way that it can be faster to find an integer in a list than a string.

This has the trade off however if you were to use Django Rest Framework that your consumers must have an understanding of what each number actually represents when working with the data. There are of course ways to solve this issue too though.

๐Ÿ‘คSayse

3๐Ÿ‘

Why not both?

Ints in the guts, so if you have the same data in multiple places you store the much smaller int, instead of the string multiple times. Anything human facing can be transformed from the int back to the string.

Smaller memory footprint, virtually 0 performance hit.

Extending Enum to a class that does these transformations for you and then inheriting from that class would be a pretty approach.

Leave a comment