将参数传递给 post_ Generation 方法 -factory_boy

问题描述 投票:0回答:1

如何将参数从工厂的

__init__
.create()
传递到Factory Boy中的
post_generation

我有一个

Project
工厂,我想将参数(如
num_participants
)从工厂的
__init__
.create()
方法传递到
post_generation
方法,但我遇到了问题。这是我的代码:

class FullProjectFactory(DjangoModelFactory):
    class Meta:
        model = Project
        exclude = ("num_participants",)  # Added a comma for tuple

    num_participants = 1
    name = Sequence(lambda n: f"full_test_project_{n}")

    @post_generation
    def create_related_objects(self, create, extracted, **kwargs):
        if not create:
            return

        # Trying to pass num_participants
        ParticipantFactory.create_batch(self.num_participants, project=self)

# Creating the project with a specific number of participants
p = FullProjectFactory.create(num_participants=10)

但是,我收到以下错误:

ParticipantFactory.create_batch(self.num_participants, project=self)
                                    ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Project' object has no attribute 'num_participants'

如何正确地将

num_participants
参数传递给
post_generation
方法?

keyword-argument factory-boy
1个回答
0
投票

解决方案

我自己解决了。 解决方案基于: https://factoryboy.readthedocs.io/en/stable/reference.html#extracting-parameters

class FullProjectFactory(DjangoModelFactory):
    class Meta:
        model = Project

    name = Sequence(lambda n: f"full_test_project_{n}")

    @post_generation
    def create_related_objects(self, create, extracted, **kwargs):
        if not create:
            return
        
        num_participants = kwargs.pop('num_participants', 1)
        ParticipantFactory.create_batch(num_participants, project=self)

并且:

p = FullProjectFactory.create(create_related_objects__num_participants=10)
© www.soinside.com 2019 - 2024. All rights reserved.