how to use lazy choice in model

26 views
Skip to first unread message

冯德玉

unread,
Dec 25, 2015, 7:02:43 AM12/25/15
to Django users
In my project, I have a dictionary in database,  i want to get choices that used in model from this dictionary,  I defined  something as follows, expect it loaded lazy:


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!


Reply all
Reply to author
Forward
0 new messages