使用外键创建多个对象

时间:2013-01-29 18:07:03

标签: python django factory-boy

我需要创建十个示例用户(User),每个用户必须有五十个文档(Doc)。如何使用factoryboy在tests.py中执行此操作?

#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 = 'demo@mail.com'
    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)

在我的tests.py中:

from django.test import TestCase
from django_dynamic_fixture import G
from factories import *

3 个答案:

答案 0 :(得分:10)

users = UserFactory.create_batch(10)
for user in users:
    doc = DocFactory.create(user=user)

答案 1 :(得分:8)

您可以使用post_generation装饰器:

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)

答案 2 :(得分:0)

对于那些使用 SQLAlchemy 的人,可以使用以下方法完成此操作(注意我使用的是Person / Address模型而不是User / Docs模型上面的例子)。

from sqlalchemy import create_engine, Integer, Text, ForeignKey, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, scoped_session, sessionmaker

import factory
from factory.alchemy import SQLAlchemyModelFactory as sqla_factory
import random

engine = create_engine("sqlite:////tmp/factory_boy.sql")
session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()

class Person(Base):
    id = Column(Integer, primary_key=True)
    name = Column(Text)
    addresses = relationship("Address", backref="person")

class Address(Base):
    id = Column(Integer, primary_key=True)
    city = Column(Text)
    street = Column(Text)
    street_number = Column(Integer)
    person_id = Column(Integer, ForeignKey('person.id'))

class AddressFactory(sqla_factory):
    class Meta:
        model = Address
        sqlalchemy_session = session
    street_number = random.randint(0, 10000)
    street = "Commonwealth Ave"
    city = "Boston"

class PersonFactory(sqla_factory):
    class Meta:
        model = Person
        sqlalchemy_session = session
    name = "John Doe"

Base.metadata.create_all(engine)
for i in range(100):
    person = PersonFactory(addresses=AddressFactory.create_batch(3))

这为每个创建的人创建了3个锻炼,每个锻炼通过person_id FK引用此人。