我有一个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'
这对我来说很有意义,但我无法弄明白如何让它发挥作用?
有人可以解释一下这里最好的方法吗?
答案 0 :(得分:2)
您可以在max_age上使用LazyAttribute,即:
class SearchPreferencesFactory(DjangoModelFactory):
min_age = FuzzyInteger(30, 90)
max_age = LazyAttribute(lambda x: FuzzyInteger(x.min_age, 100).fuzz())