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:

poetry add --group dev factory_boy


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 MimesisField class to define how fake data is generated:

import factory
from mimesis.plugins.factory import MimesisField

from account import Account

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

    username = MimesisField('username', template='l_d')
    name = MimesisField('name', gender='female')
    surname = MimesisField('surname', gender='female')
    age = MimesisField('age', minimum=18, maximum=90)
    email = factory.LazyAttribute(
        lambda instance: '{0}'.format(instance.username)
    access_token = MimesisField('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 MimesisField

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 = MimesisField("num")
    nickname = MimesisField("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.