2

我正在分享我自己的问题的解决方案,我在输入问题时意识到了解决方案......它可能对其他人有用。

在我的 Django 模型中,我有一个Gateway具有一组Nodes 的 s 并且它们都应该具有相同的Vendor.

class Vendor(models.Model):
    name = models.CharField(max_length=80, null=False)

class Gateway(models.Model):
    vendor = models.ForeignKey(Vendor, related_name='gateways')

class Node(models.Model):
    gateway = models.ForeignKey(Gateway, related_name='nodes')
    vendor = models.ForeignKey(Vendor, related_name='nodes')

现在我想用factory boy. 这里VendorFactoryNodeFactory

class VendorFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Vendor

    name = 'test_vendor'


class NodeFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Node

    # is created after this node instance
    vendor = factory.SubFactory(VendorFactory)

在创建node = NodeFactory().

问题出在GatewayFactory. 我想要的是gateway = GatewayFactory()创建一个GatewayNode实例引用的,网关和节点都使用相同的Vendor.

A尝试了几件事,但失败了。这里一枪:

class GatewayFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Gateway

    node = factory.RelatedFactory(NodeFactory, 'gateway', vendor=factory.LazyAttribute(lambda o: o.vendor))
    vendor = factory.SubFactory(VendorFactory)

问题是RelatedFactory在 GatewayFactory 和 aLazyAttribute或 aSelfAttribute在 NodeFactory 的上下文中评估之后评估。

4

1 回答 1

1

解决方案是“在 NodeFactory 的上下文中评估 GatewayFactory 和 LazyAttribute 或 SelfAttribute 之后评估RelatedFactory”

因此,我们可以引用父级来获取供应商属性:

class GatewayFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Gateway

    node = factory.RelatedFactory(NodeFactory, 'gateway', vendor=factory.SelfAttribute('gateway.vendor'))
    vendor = factory.SubFactory(VendorFactory)

这也适用于LazyAttribute

class GatewayFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Gateway

    node = factory.RelatedFactory(NodeFactory, 'gateway', vendor=factory.LazyAttribute(lambda o: o.gateway.vendor))
    vendor = factory.SubFactory(VendorFactory)
于 2016-07-07T13:50:25.420 回答