Fu Jian
Fu Jian

Reputation: 415

How do I retrieve key from value in django choices field?

The sample code is below:

REFUND_STATUS = (
    ('S', 'SUCCESS'),
    ('F', 'FAIL')
)
refund_status = models.CharField(max_length=3, choices=REFUND_STATUS)

I know in the model I can retrieve the SUCCESS with method get_refund_status_display() method. However, if I want to do it reversely like: I have 'SUCCESS' I want to find the abbreviated form 'S'. How can I do that in django or python?

Upvotes: 6

Views: 6610

Answers (3)

Kevin
Kevin

Reputation: 195

It's not entirely clear if you're asking: if I have an object with refund_type "S" how do I get "S"? If I have "SUCCESS" how do I get "S"?

In the first case, you would just use:

my_object.refund status # returns "S"

In the second case, you could convert the list of tuples into a new list of tuples with the order reversed. Then you could could convert that into a dictionary. Then you could look the value up as the key to the dictionary.

dict((v,k) for k,v in REFUND_STATUS).get("SUCCESS") # returns "S"

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599450

Convert it to a dict.

refund_dict = {value: key for key, value in REFUND_STATUS}
actual_status = refund_dict[display_status]

Upvotes: 4

wswld
wswld

Reputation: 1238

I would write something like that:

next(iter([x[0] for x in REFUND_STATUS if 'SUCCESS' in x]), None)

Upvotes: 0

Related Questions