Created
August 1, 2011 14:53
-
-
Save thanos/1118279 to your computer and use it in GitHub Desktop.
DJANGO: Dynamically generate choices for a model
This file contains hidden or 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 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