0
0
Djangoframework~30 mins

Factory Boy for test data in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Factory Boy for test data
📖 Scenario: You are building a Django app for a bookstore. You want to create test data easily for your Book model using Factory Boy.
🎯 Goal: Create a Factory Boy factory for the Book model to generate test data with fixed values and then use it to create a book instance.
📋 What You'll Learn
Create a Django model called Book with fields title (string) and author (string).
Create a Factory Boy factory class called BookFactory for the Book model.
Set default values for title and author in the factory.
Use the factory to create a Book instance.
💡 Why This Matters
🌍 Real World
Factories help developers quickly create realistic test data for Django models, making testing easier and more reliable.
💼 Career
Knowing how to use Factory Boy is valuable for Django developers writing automated tests and maintaining code quality.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book in models.py with two fields: title as CharField with max length 100, and author as CharField with max length 100.
Django
Need a hint?

Use models.CharField(max_length=100) for both fields.

2
Create the BookFactory class
In a new file factories.py, import factory and the Book model. Create a factory class called BookFactory that inherits from factory.django.DjangoModelFactory. Set the title field to 'The Great Gatsby' and the author field to 'F. Scott Fitzgerald'.
Django
Need a hint?

Remember to set class Meta with model = Book.

3
Use BookFactory to create a Book instance
In a test file or script, import BookFactory and create a book instance by calling BookFactory(). Assign it to a variable called book.
Django
Need a hint?

Call BookFactory() and assign it to book.

4
Add __str__ method to Book model
Add a __str__ method to the Book model that returns the book's title. This helps display the book nicely in Django admin and shell.
Django
Need a hint?

Define def __str__(self): inside Book and return self.title.