factory-boy 中 Factory 的可选(可空)值
Optional (nullable) value for Factory from factory-boy
我将 lazy_attribute
和 choice
与 None
一起使用,但我认为可以做得更好。
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])
factory-boy 有一个 Maybe declaration 可空字段。这里最简单的使用方法是创建一个中间字段,然后排除中间字段:
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)
我将 lazy_attribute
和 choice
与 None
一起使用,但我认为可以做得更好。
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])
factory-boy 有一个 Maybe declaration 可空字段。这里最简单的使用方法是创建一个中间字段,然后排除中间字段:
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)