Factory Boy random choice for a field with field option "choices" Factory Boy random choice for a field with field option "choices" python python

Factory Boy random choice for a field with field option "choices"


You'll not need a FuzzyAttribute.

You can either restrict the values possible and only give the int value of each product type to FuzzyChoice by doing something like this:

PRODUCT_IDS = [x[0] for x in IceCreamProduct.PRODUCT_TYPES]class IceCreamProductFactory(factory.django.DjangoModelFactory):    class Meta:        model = IceCreamProduct    type = factory.fuzzy.FuzzyChoice(PRODUCT_IDS)

It should do the work.

Please be aware that fuzzy module has been deprecated recently, see ( https://factoryboy.readthedocs.org/en/latest/fuzzy.html), you may want to use a LazyFunction instead.


Here is how I was able to do it using factory.LazyFunction as lothiraldan suggested:

import random...def get_license_type():    "Return a random license type from available choices."    lt_choices = [x[0] for x in choices.LICENSE_TYPE_CHOICES]    return random.choice(lt_choices)def get_line_type():    "Return a random line type from available choices."    lt_choices = [x[0] for x in choices.LINE_TYPE_CHOICES]    return random.choice(lt_choices)class ProductFactory(ModelFactory):    name = factory.Faker('name')    description = factory.Faker('text')    license_type = factory.LazyFunction(get_license_type)    line_type = factory.LazyFunction(get_line_type)    class Meta:        model = 'products.ProductBaseV2'


You can do as easy as this

class IceCreamProductFactory(factory.django.DjangoModelFactory):    icecream_flavour = factory.Faker(        'random_element', elements=[x[0] for x in IceCreamProduct.PRODUCT_TYPES]    )    class Meta:        model = IceCreamProduct

PS. Don't use type as attribute, it is a bad practice to use a built-in function name as an attribute