option-typefactorynullablefakerfactory-boy

Optional (nullable) value for Factory from factory-boy


I use lazy_attribute and choice with None, but I think it's possible to do it better.

import factory  # from factory-boy
from random import choice


class Device(models.Model):
    deleted_at = models.DateTimeField(null=True, blank=True)


class DeviceFactory(factory.DjangoModelFactory):
    class Meta:
        model = Device

    @factory.lazy_attribute
    def deleted_at(self):
        return choice([Faker('date_time').generate(), None])

Solution

  • factory-boy has a Maybe declaration for nullable fields. The easiest way to use it here is to create an intermediate field, and then exclude the intermediate:

    class DeviceFactory(factory.DjangoModelFactory):
        class Meta:
            model = Device
            exclude = ('is_deleted',)
    
        is_deleted = factory.Faker('pybool')
        deleted_at = factory.Maybe('is_deleted', Faker('date_time'), None)