我想使用 FactoryBoy 创建一些带有可选属性的假数据。我希望能够覆盖该属性为
None
的概率。
import random
from dataclasses import dataclass
import factory
@dataclass
class Data:
address: str | None
def optional(decider: str, declaration):
return factory.Maybe(
factory.LazyAttribute(
lambda o: random.random() <= getattr(o, decider)
),
declaration,
None,
)
class DataFactory(factory.Factory):
class Meta:
model = Data
class Params:
has_address_probability = 0.5
address = optional(
"has_address_probability",
factory.Faker("address"),
)
if __name__ == "__main__":
data = DataFactory(
# Optionally override the probability
has_address_probability=0
)
print(data)