无法使用Factory Boy和Faker创建多个Model实例



我正在尝试使用django factory boy和faker抓取django模型的多个实例。但我需要批量创建实例(而不是单个实例(。但我不能使两个属性都对应(货币的codename(。

我有一个django模型作为:

class Currency(models.Model):
"""Currency model"""
name = models.CharField(max_length=120, null=False,
blank=False, unique=True)
code = models.CharField(max_length=3, null=False, blank=False, unique=True)
symbol = models.CharField(max_length=5, null=False,
blank=False, default='$')
def __str__(self) -> str:
return self.code

我有一个工厂

import factory
from apps.Payment.models import Transaction, Currency
from faker import Faker
fake = Faker()

class CurrencyFactory(factory.django.DjangoModelFactory):
class Meta:
model = Currency
# code and name get assigned when the class is called hence if we use
# create_batch(n) we get all n object same

# code, name = fake.currency() 
code = factory.LazyAttribute(lambda _: fake.currency()[0]) 
name = factory.LazyAttribute(lambda _: fake.currency()[1]) 
symbol = '$'

我面临的问题是codename得到不同的值并且不匹配。查看faker返回的内容。

>>> from faker import Faker
>>> fake = Faker()
>>> fake.currency()
('JPY', 'Japanese yen') 

请参阅货币名称与货币代码不对应。此外,我需要使用CurrencyFactory.create_batch(5)创建至少5到6个对象。

# mismatch in code and name
NAME                            CODE
Netherlands Antillean guilder   ZAR
Western Krahn language          UGX
Colombian peso                  KHR

我想要什么

NAME                            CODE
Indian National Rupee           INR
Japanese yen                    JPY

最好的方法是通过class Params:

class CurrencyFactory(factory.model.DjangoModelFactory):
class Meta:
model = Currency
class Params:
currency = factory.Faker("currency")  # (code, name)
code = factory.LazyAttribute(lambda o: o.currency[0])
name = factory.LazyAttribute(lambda o: o.currency[1])

想法是:

  • 工厂调用Faker一次,生成currency = (code, name)参数
  • 然后,它将该参数的组件映射到模型的正确字段
  • 由于currency被声明为一个参数,它不会被传递给模型(它会自动添加到Meta.exclude

最新更新