import random import factory from user.models import UserGroup class UserGroupFactory(factory.django.DjangoModelFactory): class Meta: model = UserGroup name = factory.Sequence(lambda n: 'Klasse {}{}'.format(n+1, random.choice(['a', 'b', 'c']))) year = factory.LazyAttribute(lambda x: random.choice([2017, 2018, 2019])) is_deleted = False @factory.post_generation def users(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for user in extracted: self.users.add(user)