arooo arooo - 22 days ago 9
Python Question

Int vs String for field choices

If I have a django model that can have many types (assume they will rarely change, but new ones may perhaps be added), is it better to do it with an int?

from enum import Enum
class Places(Enum):
gym = 0
coffee_shop = 1
home = 2
garage = 3
office = 4
study = 5
shed = 6


Or is it better to do it as strings?

GYM = 'gym'
COFFEE_SHOP = 'coffee_shop'
HOME = 'home'
GARAGE = 'garage'
OFFICE = 'office'
STUDY = 'study'
SHED = 'shed'


I like strings because they're human readable (and the documentation seems to use strings like FR, JR, SR, etc) but I often see people using ints to do this.

Could someone explain why?

Answer

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.