Reputation: 1945
WHen creating a multiple choice option in Django, there seems to be two different ways to do it - option a or option b, see below. What advantages do each option have over the other. Is one generally better than another? Am I missing a better way to do it?
option a
TYPE_CHOICES=(
('teacher', ("Teacher")),
('student', ("Student")),
)
user_type = models.CharField(max_length=20, default='student', choices=TYPE_CHOICES)
option b
TYPE_CHOICES=(
(1, ("Teacher")),
(2, ("Student")),
)
user_type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, default=1)
Upvotes: 3
Views: 2643
Reputation: 495
I can suggest you a third option, it's little extra work but gives you code readability and avoid a text comparison later on.
Define an enum
class UserTypeEnum(enum.Enum):
"""Define enums for user type"""
TEACHER = 0
STUDENT = 1
in model
class Employee(models.Model)
user_type = models.IntegerField(choices=UserTypeEnum.choices(),
default=UserTypeEnum.TEACHER)
then you can do checks like
if user_type == UserTypeEnum.TEACHER:
...
Upvotes: 4
Reputation: 106553
In the old days when every byte of memory and storage was precious storing these choices as small integers made sense, but now it has no real tangible benefit. Storing it as strings makes the code more readable, makes the database more manageable and more easily migratable. I would therefore advise using strings as option values unless you really care about the small difference in storage costs.
Upvotes: 3