Generate Test Data in Django 6 or Python with Faker
Faker is a Python package that generates fake data for our application; that is, instead of manually generating test data that is usually necessary when developing any application, we can use a library that facilitates the process for us.
Using fakers we have a simple way to add test data to the database. It is especially useful during development where you need to fill the database with sample data and instead of generating it manually, it is generated automatically by the framework; in other words, it is the mechanism we have to generate that test data that we always need at the beginning of the application.
We install the package in our project with:
$ pip install Faker🎯 Why Generate Test Data?
We need test data for several reasons:
- UI and Functionality Testing: Validate interfaces (e.g., pagination) or business logic without manually creating 30 or 40 records.
- Integration/Unit Testing: Controlled and predictable data is crucial to ensure consistent test results.
- Complex Models: If you have models with many fields (e.g., a post with a title, content, date, etc.), automatic generation saves a significant amount of time.
Generate test data
There are many ways to generate test data, we can generate random numbers, names, full names, addresses, texts, etc; let's see some.
For this section, the reader is recommended to use Django Shell:
$ python manage.py shellWe create the Faker instance, which will allow us to create the test data:
from faker import Faker
fake = Faker()If we want to generate a name:
fake.first_name()A unique name:
fake.unique.first_name()Name and surname:
fake.name()Address:
fake.address()Text:
fake.text()
fake.paragraph(nb_sentences=1)Change the language:
from faker import Faker
fake = Faker(['it_IT', 'en_US', 'ja_JP'])
for _ in range(10):
print(fake.name())Random number in a range:
fake.random_int(1000, 2000)An IP:
fake.ipv4_private()These are just some of the options we have when using the Faker package, for more information consult the official documentation:
https://faker.readthedocs.io/en/master/
Script to generate test data
Our case of interest is to generate data for the application, specifically some comments, which is what we have been implementing in this section.
To generate this test data we have many ways, we could generate data by writing the script directly in Django Shell, but, to make it more interesting we are going to generate an auxiliary file; Django does not have any predefined command or file to generate test data as they do in the case of Laravel or CodeIgniter 4 using seeders, so we must generate the file that we will call like:
testcourse/create_comments.py
And it will have the following content:
mystore/create_comments.py
from faker import Faker
from comments.models import Comment
def main():
fake = Faker()
for _ in range(5):
comment = Comment.object.create(
text = fake.text()
)
comments = Comment.objects.all()
print(f'Comments in DB {comments.count()}')
if __name__ == '__main__':
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mystore.settings')
application = get_wsgi_application()
main()In the above script, we import the development server of type WSGI:
from django.core.wsgi import get_wsgi_application
In addition to creating an environment variable called DJANGO_SETTINGS_MODULE that is needed by the script so that it can use the development environment:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testcourse.settings")The next step is to create the application to start Django with the WSGI type server; we use the WSGI server imported before:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()With the previous steps, it is now possible to use the different resources of the application, such as the models, which include being able to import them:
if __name__ == '__main__':
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE','mystore.settings')
aplication = get_wsgi_application()
from comments.models import CommentSince, to use this type of resources directly in a Python script that is not going to be executed as part of a Django project but rather as an isolated file, we must establish the previous environment variable and the application.
With this, we now have the environment ready to execute any kind of commands that the environment of our application uses, in our case of interest to create the comments, an operation that we do in the function called main(). To run the above file:
$ python create_comments.pyOnce executed, we will see that some test comments have been generated.
I agree to receive announcements of interest about this Blog.
Let's learn how to generate test data using the Faker Python package in Django. With the package installed before, we'll now generate test data for the Django ecosystem.