gpt4 book ai didi

python - 将使用 SubFactory 和 LazyAttribute 创建的对象传递给 factory_boy 中的 RelatedFactory

转载 作者:太空狗 更新时间:2023-10-29 18:28:45 25 4
gpt4 key购买 nike

我在 SubFactory 调用中使用 factory.LazyAttribute 来传递在 factory_parent 中创建的对象。这很好用。

但如果我将创建的对象传递给 RelatedFactoryLazyAttribute 将无法再看到 factory_parent 并失败。

这很好用:

class OKFactory(factory.DjangoModelFactory):
class = Meta:
model = Foo
exclude = ['sub_object']

sub_object = factory.SubFactory(SubObjectFactory)

object = factory.SubFactory(ObjectFactory,
sub_object=factory.LazyAttribute(lambda obj: obj.factory_parent.sub_object))

LazyAttribute 的相同调用在此处失败:

class ProblemFactory(OKFactory):
class = Meta:
model = Foo
exclude = ['sub_object', 'object']

sub_object = factory.SubFactory(SubObjectFactory)

object = factory.SubFactory(ObjectFactory,
sub_object=factory.LazyAttribute(lambda obj: obj.factory_parent.sub_object))

another_object = factory.RelatedFactory(AnotherObjectFactory, 'foo', object=object)

相同的 LazyAttribute 调用不能再看到 factory_parent,只能访问 AnotherObject 值。 LazyAttribute 抛出错误:

AttributeError: The parameter sub_object is unknown. Evaluated attributes are...[then lists all attributes of AnotherObjectFactory]

有办法解决这个问题吗?

我不能只将 sub_object=sub_object 放入 ObjectFactory 调用中,即:

    sub_object = factory.SubFactory(SubObjectFactory)
object = factory.SubFactory(ObjectFactory, sub_object=sub_object)

因为如果我这样做:

    object2 = factory.SubFactory(ObjectFactory, sub_object=sub_object)

创建了第二个子对象,而我需要两个对象都指向同一个子对象。我试过 SelfAttribute 没有用。

最佳答案

我认为您可以利用覆盖传递给 RelatedFactory 的参数的能力来实现您想要的。

例如,给定:

class MyFactory(OKFactory):

object = factory.SubFactory(MyOtherFactory)
related = factory.RelatedFactory(YetAnotherFactory) # We want to pass object in here

如果我们事先知道 object 的值是什么,我们就可以让它像这样工作:

object = MyOtherFactory()
thing = MyFactory(object=object, related__param=object)

我们可以使用相同的命名约定将对象传递给主 Factory 中的 RelatedFactory:

class MyFactory(OKFactory):

class Meta:
exclude = ['object']

object = factory.SubFactory(MyOtherFactory)
related__param = factory.SelfAttribute('object')
related__otherrelated__param = factory.LazyAttribute(lambda myobject: 'admin%d_%d' % (myobject.level, myobject.level - 1))
related = factory.RelatedFactory(YetAnotherFactory) # Will be called with {'param': object, 'otherrelated__param: 'admin1_2'}

关于python - 将使用 SubFactory 和 LazyAttribute 创建的对象传递给 factory_boy 中的 RelatedFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33089019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com