0

I have many choice fields and each option corresponding to a number. This number will be used for later calculations.

Here is an example. I defined a dictionary which defines the value to each input:

driven_factors = {
    "Education":{
        "A": 1.29,
        "B": 0.98,
        "C": 0.72,
    },
}

and the model is like:

Education_choices= list(driven_factors.get("Education").keys())
Education= models.CharField(max_length=50, choices=Education_choices)

Unfortunately, it does not work, because Education_choices is like ['A', 'B', 'C'] other than a sequence of pairs like [('A', 'x'), ('B', 'y',...)] How should I fix this? Or are there other approaches to do this?

Edit: If transfer Education to list: it will be like

Education = (
    ('A', 1.29),
    ('B', 0.98),
    ('C', 0.72),
)

However, as designed for choices, it is the list of pairs like ('value in database', 'human-readable name'). Is it appropriate to use numberical value as the 'human-readable name', in the sense of design?

Jango
  • 852
  • 5
  • 8
  • Do you just want `items()` rather than `keys()`? Although I can't understand why you don't just make it a list or tuple in the first place. – Daniel Roseman Oct 28 '19 at 18:55
  • @DanielRoseman Do you mean `driven_factors = (('Education', (('A', 1.29), ('B', 0.98)), ('other_factors', (('factors1', 1), ('factors2', 2)))` ? – Jango Oct 28 '19 at 19:10
  • Well no, you can keep the outer one as a dict, if you really want: `{'Education': (('A', 1.29), ('B', 0.98)), 'other_factors': (('factors1', 1), ('factors2', 2)) }` – Daniel Roseman Oct 28 '19 at 19:13

1 Answers1

0

I suggest you first convert your "Education" dict to a list of tuples like so (taken from https://stackoverflow.com/a/674531/12153266) :

education_as_list = [(k, v) for k, v in driven_factors["Education"].iteritems()]

And then pass it to your model :

Education= models.CharField(max_length=50, choices=education_as_list)
Ewaren
  • 1,343
  • 1
  • 10
  • 18
  • I think you can do just `education_as_list = list(driven_factors["Education"].items())`. No need to unpack the tuple and then repack it. (the `list` is there for py3) – Tim Tisdall Oct 29 '19 at 19:43
  • @TimTisdall You are right, and I am testing it. I have to change the dict like `{1.29:'A', 1.01: 'B',}` because the Choices are defined as ('value in database', 'human-readable name'). I do not want to show numbers in forms. Only problem is, there are some entries have same numerical value. I am not sure how database can recognize that. – Jango Oct 30 '19 at 17:56