FactoryBoy / Django - 处理常量

FactoryBoy / Django - handling constants

我正在为以下 Django 模型创建工厂:

class Book(models.Model):
    tenant = models.ForeignKey('elearning.Tenant')
    book_id = models.IntegerField()
    ean = models.CharField(max_length=13, null=False)
    title = models.CharField(verbose_name="titel", max_length=200)
    author_name = models.CharField(max_length=200)
    description = models.TextField()
    price_id = models.IntegerField()
    buy_option_text = models.CharField(max_length=50)
    loan_days = models.IntegerField(null=True)
    type = 'Yindoboek'

我变成了这个工厂:

class BookFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Book

    tenant = factory.SubFactory(TenantFactory)
    book_id = factory.LazyFunction(lambda: random.randint(1, 1000))
    ean = factory.LazyFunction(
        lambda: ''.join(
            random.choice(string.ascii_uppercase) for _ in range(6)
        ) + ''.join(random.choice(string.digits) for _ in range(6))
    )
    title = factory.Faker('company')
    author_name = factory.Faker('name_male')
    description = factory.Faker('text')
    price_id = factory.LazyFunction(lambda: random.randint(1, 1000))
    buy_option_text = factory.Faker('sentence')
    loan_days = factory.LazyFunction(lambda: random.randint(1, 150))
    type = 'Yindoboek'

然而,当我尝试运行以下测试时:

    def test_factory_matches_model(self):
        """ Verify that the factory generates a valid Book instance """
        self.assertTrue(self.book)
        self.assertTrue(self.book.tenant)

它因以下错误而崩溃:

TypeError: 'type' is an invalid keyword argument for this function

FactoryBoy 似乎在 Book 模型中触发了 type 'field',这不是 Django 字段实例而是常量。

如果我从工厂中排除这个字段,测试将通过 - 但我宁愿不删除字段(重点是测试所有字段/组合) - 所以我想知道是否有办法解决这个问题问题,有人知道解决方案吗?

我找到了答案:

根据 documentation,非字段参数应放在单独的 Params class.

工作模型如下所示:

class BookFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Book

    tenant = factory.SubFactory(TenantFactory)
    book_id = factory.LazyFunction(lambda: random.randint(1, 1000))
    ean = factory.LazyFunction(
        lambda: ''.join(
            random.choice(string.ascii_uppercase) for _ in range(6)
        ) + ''.join(random.choice(string.digits) for _ in range(6))
    )
    title = factory.Faker('company')
    author_name = factory.Faker('name_male')
    description = factory.Faker('text')
    price_id = factory.LazyFunction(lambda: random.randint(1, 1000))
    buy_option_text = factory.Faker('sentence')
    loan_days = factory.LazyFunction(lambda: random.randint(1, 150))

    class Params:
        type = 'Yindoboek'