19

I am using django 1.6 and factory-boy.

class UserFactory(factory.Factory):
   class Meta:
      model = models.User

   username = factory.Sequence(lambda n: 'user%d' % n)

Here username is a simple CharField in model. So that each time I am calling UserFactory() I am saving and getting unique user named object.

In factory-boy I can use factory.SubFactory(SomeFactory).

How I can generate list of SomeFactory in ParentOfSomeFactory ?

So that, if I call ParentOfSomeFactory() I will create list of SomeFactory as well as ParentOfSomeFactory database

lxop
  • 7,596
  • 3
  • 27
  • 42
Saiful Azad
  • 1,823
  • 3
  • 17
  • 27
  • Just to make sure, even if you create a list of sub factories, the field type is still non-list type field, how you wanted to handle it? in your example, what would you do if the `lambda` would return list? – Or Duan Nov 09 '16 at 12:50
  • what would you do if the lambda would return list? So that if I call ParentOfSomeFactory() It will automatically create and save a list of SomeFactory model at database. I dont want to create it manually. – Saiful Azad Nov 09 '16 at 13:00

2 Answers2

32

Use factory.List:

class ParentOfUsers(factory.Factory):
    users = factory.List([
        factory.SubFactory(UserFactory) for _ in range(5)
    ])
Paul
  • 421
  • 5
  • 3
4

You could provide a list with factory.Iterator

import itertools
import factory

# cycle through the same 5 users
users = itertools.cycle(
    (UserFactory() for _ in range(5))
)

class ParentFactory(factory.Factory):
    user = factory.Iterator(users)
firelynx
  • 30,616
  • 9
  • 91
  • 101
Ryan Ginstrom
  • 13,915
  • 5
  • 45
  • 60