Friday, December 25, 2015

how to use lazy choice in model

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!


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/fbea0c01-9f08-4cbe-89e3-5b41b315f2ae%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment