Last active
September 15, 2015 16:04
-
-
Save singulared/035d30a0f6e9ba20a599 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Item(models.Model): | |
name = models.CharField(max_length=255) | |
def get_options(self): | |
topics = {} | |
for item_option in ItemOption.objects.select_related().all(): | |
option = item_option.option | |
topic = option.topic | |
if topic not in topics: | |
topics[topic] = [] | |
topics[topic].append( | |
{'title': option.title, | |
'value': item_option.value if item_option.item == self else None}) | |
return [{'name': topic.name, | |
'options': options} for (topic, options) in topics.items()] | |
def get_options_prefetch(self): | |
topics = [] | |
for topic in Topic.objects.prefetch_related( | |
'option_set', 'option_set__itemoption_set', 'option_set__itemoption_set__item').all(): | |
options = [] | |
for option in topic.option_set.all(): | |
try: | |
item_option = option.itemoption_set.all()[0] | |
if item_option.item == self: | |
options.append({'title': option.title, 'value': item_option.value}) | |
else: | |
options.append({'title': option.title, 'value': None}) | |
except (ItemOption.DoesNotExist, IndexError): | |
options.append({'title': option.title, 'value': None}) | |
topics.append({'name': topic.name, 'options': options}) | |
return topics |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment