Search code examples
pythondjangofactory-boy

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


I need to create some fake data using factory boy. I have the following model:

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)

I need to create a factory based on this model, and I would like the price to have a random value between 1 and 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)

The problem with this is that I am always getting the same price for every instance.


Solution

  • I was able to figure out this problem by using a lazy attribute (factory.LazyAttribute). From the docs:

    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))