class DictionaryChoices(object):
def __getattr__(self, item):
cursor = connections['default'].cursor()
cursor.execute("SELECT c_item_id,c_item_name FROM tblcommon_base_data where c_type=%s", [item])
row = cursor.fetchall()
return row
class LazyDictionary(LazyObject):
def _setup(self):
self._wrapped = DictionaryChoices()
def get_dictionary_by_types(types):
obj = LazyDictionary()
result = getattr(obj, types)
return result
def get_dictionary_string_by_types(types):
obj = LazyDictionary()
result = getattr(obj, types)
string_result = tuple([(str(i[0]), i[1]) for i in result])
return string_result
In other models, i use it as follows:
CREDENTIALS_TYPE = get_dictionary_by_types('credentials_type')
credentials_type = models.SmallIntegerField(choices=CREDENTIALS_TYPE, default=1, db_column='c_credentials_type')
it works, but it not lazy, when a insert new item to the choices , it can not load except reboot the server, maybe i can use foreignkey, but i want to know how to make it work like lazy choices, thanks for help!