gpt4 book ai didi

django - 工厂男孩 : passing model instances for a RelatedFactory

转载 作者:行者123 更新时间:2023-12-04 01:55:55 25 4
gpt4 key购买 nike

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

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 的文档,但找不到解决方案,现在隧道视野已经接管,禁止任何新的见解。

最佳答案

您正在寻找 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)

关于django - 工厂男孩 : passing model instances for a RelatedFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50683345/

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