Jamgreen
Jamgreen

Reputation: 11059

Get key value from display value from choices in Django

I have a model field with choices

CATEGORY_CHOICES = (
    (0, 'A'),
    (1, 'B'),
    (2, 'C'),
)

I'm inserting rows in my database table where the category values could be A, B, or C.

Instead of using

if category:
    if category == "A":
        category = 0
    elif category == "B":
        category = 1
    elif category == "C":
        category = 2

before inserting my rows, can I somehow use my CATEGORY_CHOICES to translate display values to key values?

Upvotes: 3

Views: 2449

Answers (2)

mishbah
mishbah

Reputation: 5607

How about this:

choices_dict = {}
for choice, value in CATEGORY_CHOICES:
    choices_dict[value] = choice

category = choices_dict[category]

Upvotes: 0

catavaran
catavaran

Reputation: 45585

Build a dict of the display_value: value pairs and get the value from it:

CATEGORIES_D = {v: k for k, v in CATEGORY_CHOICES}
category = CATEGORIES_D[category]

Upvotes: 8

Related Questions