On Saturday, 4 September 2021 04:12:55 CEST, roy cyril dosado wrote:
> hi everyone, anyone know the reason Faker (which is part of factory-boy)
> not randomizing whenever i execute it in a Factory class?i'm using the
> latest version and doing something like
> product=factory.random.random.choice(['item','item2','item3','item4']) to
> generate random value for a field, it randomly generate whenever i run it
> in a django shell, but if i generate using create_batch of factory-boy, it
> doesn't seem to generate randomize values (every create batch produces same
> item), any tips how i properly setup this function?, should i first seed or
> set something? thanks for any inputs.
>
Hi,
This is a common issue; when you write code like that, Python will
execute the `random.choice()` at import time. It's the same as writing:
RANDOMLY_CHOSEN_PRODUCT = random.choice(...)
class MyFactory(factory.Factory):
product = RANDOMLY_CHOSEN_PRODUCT
Thus, all instances from the factory will have the same value.
Instead, you should use FuzzyChoice
(
https://factoryboy.readthedocs.io/en/latest/fuzzy.html#fuzzychoice):
class MyFactory(factory.Factory):
product = factory.fuzzy.FuzzyChoice(["item1", "item2", ...])
With that declaration, the factory will fetch a random item each time it's
generating a new instance.
Hope this helps!
--
Raphaël