markwalker_
markwalker_

Reputation: 12859

How can the value of a SubFactory be set when creating a Factory object

Is it possible to set a value of a SubFactory without creating two Factory objects?

For example, I've got two Factories;

class UserFactory(factory.DjangoModelFactory):
    FACTORY_FOR = 'mysite.user'

    name = "Mark"


class MyFactory(factory.DjangoModelFactory):
    FACTORY_FOR = 'mysite.myfactory'

    user = factory.SubFactory(UserFactory)

And I want to create MyFactory() and at the same time set the value of user.name.

Do you have to create user = UserFactory.create(name="John") first or can it all be done in a one-liner from the args to MyFactory()?

At the moment in a test I've got the following;

def setUp(self):
    user = factories.UserFactory(name="John")
    myfactory = factories.MyFactory(user=user)

Upvotes: 4

Views: 2141

Answers (1)

alecxe
alecxe

Reputation: 473893

According to documentation, you can define SubFactory fields right in the external factory definition:

factories.MyFactory(user__name="John")

Hope that helps.

Upvotes: 4

Related Questions