Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple objects with foreign key

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 *
like image 821
ringfirebug Avatar asked Jan 29 '13 18:01

ringfirebug


2 Answers

users = UserFactory.create_batch(10)
for user in users:
    doc = DocFactory.create(user=user)
like image 96
Bernhard Vallant Avatar answered Oct 16 '22 22:10

Bernhard Vallant


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)
like image 42
guettli Avatar answered Oct 16 '22 21:10

guettli