如何使用 Factory Boy 为模型字段生成随机数

How to generate a random number for a model field using Factory Boy

我需要使用 factory boy 创建一些假数据。我有以下型号:

class Fabric(models.Model):
    title = models.CharField(max_length=200, blank=True)
    description = models.CharField(max_length=200, blank=True)
    price = models.DecimalField(decimal_places=2, max_digits=10, null=True, blank=False)

我需要根据这个模型创建一个工厂,我希望价格有一个介于 1 和 100 之间的随机值。

class FabricFactory(DjangoModelFactory):
    class Meta:
        model = Fabric

    title = factory.Faker('name')
    description = factory.Faker('catch_phrase')
    price = random.randrange(MIN_PRICE, MAX_PRICE + 1)

这个问题是我总是为每个实例获得相同的价格。

我使用 lazy attribute (factory.LazyAttribute) 解决了这个问题。来自文档:

Most factory attributes can be added using static values that are evaluated when the factory is defined, but some attributes (such as fields whose value is computed from other elements) will need values assigned each time an instance is generated.

class FabricFactory(DjangoModelFactory):
    class Meta:
        model = Fabric

    title = factory.Faker('name')
    description = factory.Faker('catch_phrase')
    price = factory.LazyAttribute(random.randrange(MIN_PRICE, MAX_PRICE + 1))

就我而言,LazyAttribute 没有用。

我发现使用 factory boy 生成 10 位随机数的最佳方法是这样的:

import factory.fuzzy

class CustomUserFactory(DjangoModelFactory):
        phone_number = factory.fuzzy.FuzzyInteger(9000000000, 9999999999)

里面提供的参数FuzzyInteger()是生成随机数的下限和上限

您也可以使用 python 提供商。

class MyModel(factory.django.DjangoModelFactory)
  number_field = factory.Faker('pyint', min_value=0, max_value=1000)
  class Meta:
    model = SomeModel

Documentation