If you want to generate auto-generated dummy data for a model in Django, you can use third-party libraries such as Faker
or Factory Boy
to create and populate instances of your model with random or realistic data.
First you would need to install the Faker
library :
pip install Faker
Next you can create a custom command to generate dummy data for the Person model. Click here to see how to create a custom command in Django.
Create a file named generate_Person_data
in the app/management/commands
folder and type in the following code to generate dummy data for Person
model :
from django.core.management.base import BaseCommand
from faker import Faker
from modeldemo.models import Person
class Command(BaseCommand):
help = 'Generate and insert dummy data for the Person model'
def add_arguments(self, parser):
parser.add_argument('--entries', type=int, help='The number of rows to insert')
def handle(self, *args, **kwargs):
fake = Faker()
num_entries = kwargs['entries']
if num_entries is None:
self.stdout.write(self.style.SUCCESS('No --entries argument provided. Using the default of 10 entries.'))
num_entries = 10
for _ in range(num_entries):
first_name = fake.first_name()
last_name = fake.last_name()
birth_date = fake.date_of_birth(minimum_age=18, maximum_age=80)
Person.objects.create(
first_name=first_name,
last_name=last_name,
birth_date=birth_date,
)
self.stdout.write(self.style.SUCCESS(f'Successfully inserted {num_entries} dummy entries for the Person model.'))
You can generate dummy data by running the following command :
python manage.py generate_Person_data --entries 1
If the command is run without passing the entries argument, then 10 dummy records would be generated.
python manage.py generate_Person_data
Now, if you try to get the Person objects, you will be able to see the dummy data in it.
Person.objects.all()
Similarly, you can create any amount of dummy data for any of your models.