DEV Community

Hiro Takkii
Hiro Takkii

Posted on

Change faker depending on the value of FuzzyChoice

I use factory_bot and faker with Django.

I want to create User with random gender, and also name related to the gender.(Of course, name does not define gender.)

To do so, I use FuzzyChoices and factory.lazy_attribute

from django.contrib.auth import get_user_model import factory from accounts.models import Gender from factory import fuzzy from faker import Faker class UserFactory(factory.django.DjangoModelFactory): class Meta: model = UserModel gender = fuzzy.FuzzyChoice([Gender.FEMALE, Gender.MALE]) @factory.lazy_attribute def name(self): locale = "ja_JP" if self.gender == Gender.FEMALE: return Faker(locale).name_female() else: return Faker(locale).name_male() 
Enter fullscreen mode Exit fullscreen mode

Thanks.

Top comments (0)