Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 716
markwalker_ Avatar asked Sep 18 '25 16:09

markwalker_


1 Answers

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

factories.MyFactory(user__name="John")

Hope that helps.

like image 192
alecxe Avatar answered Sep 20 '25 07:09

alecxe