Skip to content

Instantly share code, notes, and snippets.

@mlalic
Created June 17, 2014 16:23
Show Gist options
  • Select an option

  • Save mlalic/eda162cd0a5ce863691b to your computer and use it in GitHub Desktop.

Select an option

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.
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()))
@shacker
Copy link

shacker commented Aug 3, 2017

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())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment