我用工厂男孩做模特。另一个模型有一个外键,该模型的第一个obj用于模型的字符串表示。示例结构:
class A(models.Model):
...
def __str__(self):
return self.reverseForeignKey_set.first().name
class AFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.A
some_attribute = factory.RelatedFactory(
ReverseModelFactory,
'a',
)
但是当我用factory_boy来创建时,它会给我一个错误:
^{pr2}$有什么我能做的吗?比如只为工厂男孩在模型A上重写str方法?在
您遇到这样的问题是因为
A
模型实例的创建时间早于ReverseModel
实例。在正如工厂男孩的文件所说:
见http://factoryboy.readthedocs.io/en/latest/reference.html#post-generation-hooks
首先,您应该创建
ReverseModel
,然后创建A
模型实例。 正如工厂男孩文件中所说:因此,您可以为FK模型定义工厂,并将其定义为工厂中的子工厂。在
在这种情况下,将首先创建ReverseModelFactory对象,该对象应该可以解决您的问题。 有关详细信息,请参见http://factoryboy.readthedocs.io/en/latest/recipes.html。在
我还需要注意的是,如果你想处理很多字段,你应该使用后生成钩子:
^{pr2}$有关详细信息,请参见http://factoryboy.readthedocs.io/en/latest/recipes.html#simple-many-to-many-relationship。在
相关问题 更多 >
编程相关推荐