使用Factoryboy的模型中的字段之间的依赖关系

时间:2017-12-05 20:57:48

标签: django python-3.x factory-boy

我有一个Django模型,我想用Factoryboy测试。

这里的问题是这些字段相互依赖。

class SearchPreferences(models.Model):
    min_age = models.PositiveSmallIntegerField(null=True)
    max_age = models.PositiveSmallIntegerField(null=True)

在这种情况下,max_age不能小于min_age

class SearchPreferencesFactory(DjangoModelFactory):
    min_age = FuzzyInteger(30, 90)
    max_age = FuzzyInteger(SelfAttribute('min_age'), 100)

这是我试过的,它应该在max_age和100之间给我min_age的值,但是会发生什么是TypeError:

TypeError: unsupported operand type(s) for +: 'SelfAttribute' and 'int'

这对我来说很有意义,但我无法弄明白如何让它发挥作用?

有人可以解释一下这里最好的方法吗?

1 个答案:

答案 0 :(得分:2)

您可以在max_age上使用LazyAttribute,即:

class SearchPreferencesFactory(DjangoModelFactory):
    min_age = FuzzyInteger(30, 90)
    max_age = LazyAttribute(lambda x: FuzzyInteger(x.min_age, 100).fuzz())