Skip to content

Instantly share code, notes, and snippets.

@thanos
Created August 1, 2011 14:53
Show Gist options
  • Select an option

  • Save thanos/1118279 to your computer and use it in GitHub Desktop.

Select an option

Save thanos/1118279 to your computer and use it in GitHub Desktop.
DJANGO: Dynamically generate choices for a model
class DynamicChoice(object):
"""
Trivial example of creating a dynamic choice
"""
def __iter__(self):
for choice in self.generate():
if hasattr(choice,'__iter__'):
yield (choice[0], choice[1])
else:
yield choice, choice
def __init__(self):
"""
If you do it here it is only initialized once. Then just return generated.
"""
import random
self.generated = [random.randint(1,100) for i in range(10)]
def generate(self):
"""
If you do it here it is initialized every time the iterator is used.
"""
import random
return [random.randint(1,100) for i in range(10)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment