Created
June 17, 2014 16:23
-
-
Save mlalic/eda162cd0a5ce863691b to your computer and use it in GitHub Desktop.
A FuzzyAttribute for factory_boy to choose a random foreign key instance of 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 FuzzyForeignKeyChoice(factory.fuzzy.BaseFuzzyAttribute): | |
| """ | |
| A custom FuzzyAttribute for ``factory_boy`` which choses a random instance | |
| of a model for a new instance's field value. | |
| """ | |
| def __init__(self, model): | |
| self.model = model | |
| def get_queryset(self): | |
| """ | |
| Return a query set of instances of the given model. | |
| By default returns a queryset representing all instances. | |
| """ | |
| return self.model.objects.all() | |
| def fuzz(self): | |
| # At the moment of fuzzying the field, obtain a query set of the | |
| # given model and return a random value | |
| return random.choice(list(self.get_queryset())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A perhaps simpler way to generate a random FK with FactoryBoy, without the need for this class:
foo = factory.LazyAttribute(lambda a: MyModel.objects.order_by('?').first())