I need to create ten sample users (User
) and each of them must have fifty documents (Doc
). How to do this in tests.py using factoryboy?
#factories.py
from app_name.models import *
import factory
from datetime import datetime, timedelta, time
from django.contrib.auth.models import User
class UserFactory(factory.Factory):
FACTORY_FOR = User
username = factory.Sequence(lambda n: 'User ' + n)
email = '[email protected]'
password = '1234567'
class DocFactory(factory.Factory):
FACTORY_FOR = Doc
user = factory.SubFactory(UserFactory)
kategories = '1'
doc_number = '12345678'
date_join = factory.Sequence(lambda n:(datetime.now() + timedelta(days=n)).date(), int)
in my tests.py:
from django.test import TestCase
from django_dynamic_fixture import G
from factories import *
users = UserFactory.create_batch(10)
for user in users:
doc = DocFactory.create(user=user)
You can use a post_generation
decorator:
class UserFactory(factory.Factory):
...
@factory.post_generation
def create_docs(self, create, extracted, **kwargs):
if not create:
return
for i in range(50):
doc = DocFactory.create(user=self)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With