6

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?

Fu Jian
  • 395
  • 2
  • 12

3 Answers3

4

Convert it to a dict.

refund_dict = {value: key for key, value in REFUND_STATUS}
actual_status = refund_dict[display_status]
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 4
    actually, you will need to first reverse the order, ie, reversed_refund_dict = {value: key for key, value in REFUND_STATUS} – zsquare Aug 03 '15 at 08:22
  • `refund_dict['SUCCESS']` would result in error. OP wanted to get the key by value. – wswld Aug 03 '15 at 08:22
  • Thanks, man! But when I call it in my python shell with **dict(REFUND_STATUS)** it said: 'tuple' object is not callable. – Fu Jian Aug 03 '15 at 08:25
1

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"
Kevin
  • 175
  • 1
  • 9
0

I would write something like that:

next(iter([x[0] for x in REFUND_STATUS if 'SUCCESS' in x]), None)
wswld
  • 1,218
  • 15
  • 32