Search code examples
pythondjangofactoryfactory-boy

Django FactoryBoy: fill modelfield with choices throws error


I am working on a factory for a model and I am trying fill a field that has a list of choices. When I attempt to create an object with the Factory where I attempt to fill in a random choice from the choice list, an exception is thrown:

TypeError: 'choice' is an invalid keyword argument for this function

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/factory/base.py", line 551, in build
    return cls._generate(enums.BUILD_STRATEGY, kwargs)
  File "/usr/local/lib/python2.7/dist-packages/factory/base.py", line 505, in _generate
    return step.build()
  File "/usr/local/lib/python2.7/dist-packages/factory/builder.py", line 279, in build
    kwargs=kwargs,
  File "/usr/local/lib/python2.7/dist-packages/factory/base.py", line 312, in instantiate
    return self.factory._build(model, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/factory/base.py", line 531, in _build
    return model_class(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 571, in __init__
    raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'choice' is an invalid keyword argument for this function

Versions used:

django==1.11
factory-boy==2.9.2
python==2.7.12

The (cropped) model:

class Server(models.Model):

    TEST = 'test'
    ACCEPT = 'accept'

    SERVER_TYPES = (
        (TEST, _("Testing Server")),
        (ACCEPT, _("Acceptation Server"))
    )

    type = models.CharField(_("Server type"), max_length=50, choices=SERVER_TYPES)

The (cropped) factory:

class ServerFactory(factory.DjangoModelFactory):

    type = factory.Faker('random_element', elements=[choice[0] for choice in Server.SERVER_TYPES)

    class Meta:
        model = Server

In stead of using Faker('random_element, elements=[..]), I've also tried using the LazyFunction:

def get_server_type():
    choices = [choice[0] for choice in Server.SERVER_TYPES]
    return random.choice(choices)

class ServerFactory(factory.DjangoModelFactory):

    organization = factory.SubFactory(OrganizationFactory)
    type = factory.LazyFunction(get_server_type)

    .. Meta ..

This also throws the same error. I also cannot find any real other alternatives to fix this. Any suggestions how I can fill the type field with one of the SERVER_TYPES choices while using the factory package?


Solution

  • Could you try this instead?

    from random import choice
    type = factory.LazyAttribute(lambda x: choice(Server.SERVER_TYPES)[0])
    

    Old comment based on initial description of the question:

    it should be type = factory.Faker('random_element', elements=[choice[0] for choice in Server.SERVER_TYPES])