Integration with factory_boy

New in version 15.0.0.

You no longer require any third-party packages to integrate Mimesis with factory_boy.

Mimesis requires factory_boy to be installed, but it’s not a hard dependency. Therefore, you’ll need to install it manually, like this:

poetry add --group dev factory_boy

Alternatively, you can include it as an extra when installing Mimesis itself, like so:

poetry add --group dev mimesis[factory]


Look at the example below and you’ll understand how it works:

class Account(object):
    def __init__(self, username, email, name, surname, age):
        self.username = username = email = name
        self.surname = surname
        self.age = age

Now, use the FactoryField class to define how fake data is generated:

import factory
from mimesis.plugins.factory import FactoryField

from account import Account

class AccountFactory(factory.Factory):
    class Meta(object):
        model = Account

    username = FactoryField('username', template='l_d')
    name = FactoryField('name', gender='female')
    surname = FactoryField('surname', gender='female')
    age = FactoryField('age', minimum=18, maximum=90)
    email = factory.LazyAttribute(
        lambda instance: '{0}'.format(instance.username)
    access_token = FactoryField('token', entropy=32)

See factory_boy documentation for more information about how to use factories.


You can also define custom field handlers for your factories. To do this, you need to define an attribute named field_handlers in the Params class of your factory.

Just like this:

import factory
from mimesis.plugins.factory import FactoryField

class FactoryWithCustomFieldHandlers(factory.Factory):
    class Meta(object):
        model = Guest # Your model here

    class Params(object):
        field_handlers = [
            ("num", lambda rand, **kwargs: rand.randint(1, 99)),
            ("nick", lambda rand, **kwargs: rand.choice(["john", "alice"])),

    age = FactoryField("num")
    nickname = FactoryField("nick")

See Custom Field Handlers for more information about how to define custom field handlers.

Factories and pytest

We also recommend to use pytest-factoryboy. This way it will be possible to integrate your factories into pytest fixtures.