Skip to content

Instantly share code, notes, and snippets.

@singulared
Last active September 15, 2015 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save singulared/035d30a0f6e9ba20a599 to your computer and use it in GitHub Desktop.
Save singulared/035d30a0f6e9ba20a599 to your computer and use it in GitHub Desktop.
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