在父级和相关工厂

时间:2016-07-07 13:48:03

标签: django factory-boy

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

在我的Django模型中,我有一个Gateway,其中包含一组Node个,并且它们都应该具有相同的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,网关和节点使用相同的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

问题是在LazyAttribute之后评估了GatewayFactory,并在NodeFactory的上下文中评估了SelfAttributeprivate void buildComment() { StringBuilder comment = new StringBuilder(); // Append comments from each tab for (Tab t : detailsPane.getTabs()) { t.getComment(comment); } }

1 个答案:

答案 0 :(得分:0)

  

解决方案是“在NodeFactory 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)