Django Factory Boy 循环 return 相同的值

Django Factory Boy loop return same value

我正在尝试从循环中生成假对象,但总是returns相同的对象

utilities.py:

...
for _ in range(number_objects):
    try:
        element = app_factories.UserFactory()
        print(element)
    except Exception as e:
        print(e)
        print(type(e))
...

factories.py

from faker import Faker
from factory.fuzzy import FuzzyChoice
from factory.django import DjangoModelFactory

fake = Faker(['es-ES'])

class UserFactory(DjangoModelFactory):
  name = fake.name()
  email = '{}@mailcom'.format(slugify(name))
  height = fake.numerify(text='1##')
  friend = FuzzyChoice(app_models.User.objects.all())

  class Meta:
    model = app_models.User

可能是种子或生成器的问题,但我不知道如何解决。 有人可以帮我吗? 提前致谢。

问题是对 faker 的调用是在模块导入时计算的。

您所写的等同于:

fake = Faker(['es-ES'])
name = fake.name()  # "John Doe"
email = '{}@mailcom'.format(slugify(name))  # 'johndoe@mailcom'
height = fake.numerify(text='1##')  # 123
friend = FuzzyChoice(app_models.User.objects.all())  # Lazy

class UserFactory(DjangoModelFactory):
  ...
  name = "John Doe"
  email = 'johndoe@mailcom'
  height = 123
  friend = FuzzyChoice(app_models.User.objects.all())

改为使用:

class UserFactory(DjangoModelFactory):
  ...
  name = factory.Faker("name")
  email = factory.LazyAttribute(lambda o: '{}@mailcom'.format(slugify(o.name)))

你会在我的回答中找到关于你的代码和使用 FactoryBoy 助手之间区别的更详细解释:Django Tests - User Factory with create_batch