Skip to content Skip to sidebar Skip to footer

In Factory Boy, How To Join Strings Created With Faker?

I want to use Factory Boy and its support for Faker to generate strings from more than one provider. e.g. combining prefix and name: # models.py from django.db import models class

Solution 1:

You can use the (essentially undocumented) exclude attribute to make your first approach work:

classPersonFactory(factory.Factory):
    classMeta:
        model = Person
        exclude = ('prefix', 'name')

    # Excluded
    prefix = factory.Faker('prefix')
    name = factory.Faker('name')

    # Shows up
    full_name = factory.LazyAttribute(lambda p: '{} {}'.format(p.prefix, p.name))

You could also just use factory.LazyAttribute and generate it all in one go by directly using faker:

from faker import Faker

fake = Faker()

classPersonFactory(factory.Factory):
    classMeta:
        model = Person

    # Shows up
    full_name = factory.LazyAttribute(lambda p: '{} {}'.format(fake.prefix(), fake.name()))

The downside of this approach is that you you don't have easy access to the person's prefix or name.

Post a Comment for "In Factory Boy, How To Join Strings Created With Faker?"