factory_boy:传递RelatedFactory的模型实例

时间:2018-06-04 14:53:41

标签: django factory-boy

我认为不是以ATTR__SUBATTR的形式将数据传递给工厂的RelatedFactory,您也应该能够直接传递已经存在的实例。除非我遗漏了一些非常明显的东西,否则这似乎不起作用。 看看:

class Owner(models.Model):
    name = models.CharField()

class Item(models.Model):
    name = models.CharField()
    owner = models.ForeignKey(Owner, null = True, related_name = 'items')

class ItemFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Item

class OwnerFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Owner
    items = factory.RelatedFactory(ItemFactory, 'owner')

item = Item.objects.create(name='Foo')
alice = OwnerFactory(name='Alice', items__name='Bar')
alice.items.all()
<QuerySet [<Item: Bar>]>
bob = OwnerFactory(name='Bob', items=item) # or items = [item] doesn't matter
bob.items.all()
<QuerySet []>

一直在努力让我的工厂变得更好,干涸并且遇到了这个障碍。写了我自己的RelatedFactory改编版,它允许一次处理多个值,如果你在这个过程中创建新对象,它可以正常工作 - 但是如果你使用已经存在的对象则不行。

有效的示例:OwnerFactory(items__name=['Foo','Bar'])=> Foo and Bar in owner.items
不起作用的示例:OwnerFactory(items=[foo,bar])=> owner.items is empty
请注意,我在顶部的大例子中使用了默认的RelatedFactory。

我整天都在查看factory_boy的文档,但是现在找不到解决方案和隧道视图,禁止任何新见解。

1 个答案:

答案 0 :(得分:4)

您正在寻找http://factoryboy.readthedocs.io/en/latest/recipes.html#simple-many-to-many-relationship

class ItemFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Item

class OwnerFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Owner

    @factory.post_generation
    def items(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of items were passed in, use them
            for item in extracted:
                self.items.add(item)