How do I get the string value of the tuple in Django

This sounds like a noob question, I just want to ask how do I get the string value of this tuple.

USER_TYPE_CHOICES = (
    (1, 'PQA'),
    (2, 'Tester'),
    (3, 'Test Lead'),
    (4, 'Test manager'),
    (5, 'Senior Test Manager'),
    (6, 'admin'),
)
user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)

When I call the value as:

<h1> {{ user.user_type }} </h1>

It shows up as the int value and not the string.

It sounds very simple but I can't seem to find it on the python documentation.

Upvotes: 2

Views: 886

Answers (3)

Jun Zhou
Jun Zhou

Reputation: 1117

Using PositiveSmallIntegerField will only show index numbers, you can use models.CharField()

USER_TYPE_CHOICES = (
    ('PQA', 'PQA'),
    ('Tester', 'Tester'),
    ('Lead', 'Test Lead'),
    ('Manager', 'Test manager'),
    ('SeniorManager', 'Senior Test Manager'),
    ('Admin', 'admin'),
)

user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICES)

You may need to recreate the database and do the migration operations following this link to make the new string choices working.

Upvotes: 1

John
John

Reputation: 770

To do this I prefer to use a method to get the attribute, and constants to declare choices, like Django documentation.

Like this example:

Class ModelName(models.Model):
    ...
    PQA = 1
    TESTER = 2
    TEST_LEAD = 3
    TEST_MANAGER = 4
    SENIOR_TEST_MANAGER = 5
    ADMIN = 6
    USER_TYPE_CHOICES = (
        (1, 'PQA'),
        (2, 'Tester'),
        (3, 'Test Lead'),
        (4, 'Test manager'),
        (5, 'Senior Test Manager'),
        (6, 'admin'),
    )
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)

    def get_user_type(self):
        return dict(self.USER_TYPE_CHOICES).get(self.user_type)

On template:

<h1> {{ user.get_user_type }} </h1>

This allows you to use the constants in your code:

if user_instance.user_type is ModelName.TESTER:
    ...

Which is easier to read.

Upvotes: 0

user12966778
user12966778

Reputation:

try this

USER_TYPE_CHOICES = (
    ('PQA', 'PQA'),
    ('Tester', 'Tester'),

)
user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)

Upvotes: 0

Related Questions