user.email after user = UserFactory() is executed?import factory from myapp.models import User class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda n: f'user{n}') email = factory.LazyAttribute(lambda obj: f'{obj.username}@example.com') user = UserFactory()
The username is generated using factory.Sequence starting at 0, so the first user has username user0. The email uses LazyAttribute to build the email from the username, so it becomes user0@example.com.
Option A is missing a comma between the string and the keyword argument in factory.Faker('random_number' digits=3), causing a syntax error.
order.total after creation?order.total be after order = OrderFactory()?import factory from myapp.models import Order class OrderFactory(factory.django.DjangoModelFactory): class Meta: model = Order quantity = 3 price_per_item = 10 total = factory.LazyAttribute(lambda o: o.quantity * o.price_per_item) order = OrderFactory()
The total field uses LazyAttribute to multiply quantity (3) by price_per_item (10), resulting in 30.
profile = ProfileFactory() cause a RecursionError?import factory from myapp.models import Profile, User class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda n: f'user{n}') class ProfileFactory(factory.django.DjangoModelFactory): class Meta: model = Profile user = factory.SubFactory(UserFactory) friend = factory.SubFactory('myapp.factories.ProfileFactory') profile = ProfileFactory()
The friend field uses SubFactory referencing ProfileFactory itself, causing infinite recursion when creating a profile.
Book with two Author objects, each having different names. Which factory setup achieves this correctly?from myapp.models import Book, Author import factory class AuthorFactory(factory.django.DjangoModelFactory): class Meta: model = Author name = factory.Sequence(lambda n: f'Author {n}') class BookFactory(factory.django.DjangoModelFactory): class Meta: model = Book title = 'My Book' authors = factory.RelatedFactoryList(AuthorFactory, related_name='book', size=2)
Option B uses RelatedFactoryList with size=2 to create two authors. The Sequence in AuthorFactory ensures different names. This is the correct pattern.
