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)
Comments