What is the difference between these two codes?
Code 1:
class YearInSchool(models.TextChoices):
FRESHMAN = 'FR', _('Freshman')
SOPHOMORE = 'SO', _('Sophomore')
JUNIOR = 'JR', _('Junior')
SENIOR = 'SR', _('Senior')
GRADUATE = 'GR', _('Graduate')
Code 2:
class YearInSchool(models.IntegerChoices):
FRESHMAN = 1, _('Freshman')
SOPHOMORE = 2, _('Sophomore')
JUNIOR = 3, _('Junior')
SENIOR = 4, _('Senior')
GRADUATE = 5, _('Graduate')
Why does everybody use models.TextChoices, although using models.IntegerChoices and models.PositiveSmallIntegerField will take less memory?
Am I missing something that I am not understanding well?
When to use models.TextChoices over models.IntegerChoices or vice versa?
I am asking this question because at every django code I am reading, the programmer uses text choices. I am talking generally, even for django versions earlier than 3.
The choices are on the following format:
choice_format = (db_format, display_format)
The db_format is what's saved to the DB.
The display_format is what's displayed when you call get_<FOO>_display
You basically choose which to save in the DB, the integer or the text choice. The problem is when your model is serialized, if you have field year with choices of YearInSchool(models.IntegerChoices):, you'll have this:
"year": 1
in your JSON, but you expect it to show "Freshman", Of course you can manipulate this on the serializer level to show freshman if the year is 1.
IntegerChoices are much faster when they are looked up, but the are too ambiguous. If I were you, I'd use IntegerChoices every single time and manipulate the response through the serializer to show the text instead of the integer itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With