2016-12-05 96 views
0

我使用工廠男孩來測試某些模型(不是django),我在想如何顯示包含另一個工廠的多個實例的列表的字段。例如具有clases 用戶如何使用factory_boy中的實例列表創建字段

class User: 
    name = StringType(required=True) 

class Group: 
    name = StringType(required=True) 
    user = ModelType(User) 

我想顯示的場稱爲用戶工廠包含所有到這樣的用戶所屬的組內。在運行工廠時默認顯示兩個組['group1','group2']。

class UserFactory: 
    name = factory.Faker('first_name') 
    groups = factory.RelatedFactory(GroupFactory, 'user') 

    class Meta: 
     model = User 


class GroupFactory: 
    name = factory.Faker('word') 
    user = factory.SubFactory(UserFactory) 

    class Meta: 
     model = Group 

我試過使用上面顯示的相關工廠,但我不知道如何定義相關字段的默認值。有誰能爲這個問題帶來一些啓示,有沒有任何工廠男孩的導師?

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

    name = "John Doe" 

    @factory.post_generation 
    def groups(self, create, extracted, **kwargs): 
     if not create: 
      # Simple build, do nothing. 
      return 

     if extracted: 
      # A list of groups were passed in, use them 
      for group in extracted: 
       self.groups.add(group) 

http://factoryboy.readthedocs.io/en/latest/recipes.html#simple-many-to-many-relationship

如果您創建UserFactory像文檔中,然後就可以使用UserFactory時提供組:

回答

0

這在工廠男孩文檔的常用食譜的一部分被提及您可以使用它像這樣:

group1 = GroupFactory() 
UserFactory.create(groups=[group1,]) 

如果要由工廠創建的每個用戶提供默認組,日恩,你可以添加一個else子句的if:

@factory.post_generation 
def groups(self, create, extracted, **kwargs): 
    if not create: 
     # Simple build, do nothing. 
     return 

    if extracted: 
     # A list of groups were passed in, use them 
     for group in extracted: 
      self.groups.add(group) 
    else: 
     self.groups.add(GroupFactory(name='default group 1')) 

的例子在文檔中使用Django,所以我把它用在回答爲好。

相關問題