Login

Dictionary of choices based in models

Author:
marcoslhc
Posted:
April 4, 2010
Language:
Python
Version:
1.1
Tags:
forms choicefield zip list-of-tuples orm-and-forms
Score:
1 (after 1 ratings)

Sometimes we need to build a ChoiceField from data in a Model or more than just one model via fk's but the ModelChoiceField is not that flexible. So, in order to obtain a list of tuples with pk and a descriptive text for the choices parameter of the ChoiceField use this little function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def prepare_choice_list(keys_QuerySet, values_QuerySet, foreignKey_field, localKey_field):
# gets the values of the FK in the model as a list of tuples in the form:
# [(row1_FKValue,),(row2_FKValue,),...]
# uses distinct() to not repeat values in the option list
        a = keys_QuerySet.distinct().values(foreignKey_field)

#and then expand the tuples in a single list of elements
	a = [v[foreignKey_field] for v in a]

	b = []

	for v in a:

# search the "human readable" values in the related model 
# for the keys before extracted
		bs = eval("values_QuerySet.get(%s__iexact = '%s').__unicode__()"%(localKey_field,v))

		b.append(bs)

#inserts a empty option as the default (first) option in the select
#just comment the two lines below if you don't want it
	a.insert(0,"")
	b.insert(0,"----------")

# the zip funtions joins two lists in the form [(list1_value, list2_value),...]
	return zip(a,b)

More like this

  1. Timezone choice field for select box by jmunro 3 years, 2 months ago
  2. A Lazy ChoiceField implementation by lsbardel 5 years, 7 months ago
  3. A Lazy ModelChoiceField implementation by alecdotico 1 year, 10 months ago
  4. Rendering radio-buttons with icons instead of labels by jeverling 5 years, 2 months ago
  5. Getting dynamic model choices in newforms by ubernostrum 8 years, 2 months ago

Comments

Please login first before commenting.