12

我需要创建 10 个示例用户 ( User),每个用户必须有 50 个文档 ( 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 *
4

4 回答 4

15
users = UserFactory.create_batch(10)
for user in users:
    doc = DocFactory.create(user=user)
于 2013-01-29T22:48:19.940 回答
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)
于 2014-08-12T14:31:47.213 回答
0

您可以简单地执行 batch_create 以便为每个 DocFactory 对象创建新的 UserFactory 对象

`DocFactory.create_batch(10)`
于 2021-09-23T09:54:46.970 回答
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_idFK 引用该人。

于 2017-05-09T16:25:41.153 回答