Populating the Database with Fake Data

Learn to populate your Django database with fake data so that you can play with that for the rest of the course.

Model creation

Now that you have set up your Django Project, you will have to define and create the models that you will use in your Django Admin interface. You will create model classes in the models.py file present in the /sample_app folder. There are three models that will be created and used throughout the course: Author, Question, and Choice.

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=200)
    createdDate = models.DateTimeField(auto_now_add=True)
    updatedDate = models.DateTimeField(auto_now=True)

    def __str__(self):
        return u'%s' % self.name

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    refAuthor = models.ForeignKey(Author, on_delete=models.CASCADE)
    createdDate = models.DateTimeField(auto_now_add=True)
    updatedDate = models.DateTimeField(auto_now=True)

    def __str__(self):
        return u'[%s] : %s' % (self.refAuthor, self.question_text)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    createdDate = models.DateTimeField(auto_now_add=True)
    updatedDate = models.DateTimeField(auto_now=True)

    def __str__(self):
        return u'%s : %s' % (self.question, self.choice_text)

You will need to register your sample_app application inside the list of INSTALLED_APPS present in \helloworld\settings.py.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sample_app'
]

And now you will create new models inside your database by launching the following migration commands:

python manage.py makemigrations
python manage.py migrate

These models are the modelization of a simple quiz: an Author can write multiple Questions and every Question can have multiple Choices. The following diagram shows that relationship:

Creating fake data

With your models now ready, it is time to create some fake data to develop and test your Django Admin interface. To do this, you will require model_bakery and faker python packages, which are already installed in our excitable environment using the following commands (but when you press the run button in code widget below, it will run these commands for you):

pip install model_bakery
pip install Faker

For populating the data you have the createFakeData.py script (see the code widget below). The only thing you need to know about this script is that it populates the database with the models and their attributes (defined above in the diagram) with random data.

You will run this script with the help of the following command, but this has already been set for you and you will just need to press Run in the code widget below.

python createFakeData.py

After this step, you should find generated data in your database. To show data in your Django Admin, you need to register your models in the sample_app\admin.py:

from django.contrib import admin
from sample_app.models import *

## Register your models here.
admin.site.register(Author)
admin.site.register(Question)
admin.site.register(Choice)

Now you will see your models on the Django Admin page.

By default, Django adds an ā€˜sā€™ character at the end of the model name, to indicate the plural form (since we can have multiple results inside a model). If you want to change the plural spelling, you can set a verbose_name_plural in the class Meta in your sample_app\model.py file like this:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=200)
    createdDate = models.DateTimeField(auto_now_add=True)
    updatedDate = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "The Authors"

    def __str__(self):
        return u'%s' % (self.name)

The same can be done for the Question and Choice models.

Try it yourself

In the code widget below, try out the things you learned in this lesson:

  • Create the model definitions and change their names in sample_app\model.py.
  • Register your models inside sample_app\admin.py.
  • Register your sample_app application inside the list of INSTALLED_APPS present in \helloworld\settings.py.
  • The migrations commands will automatically be executed for you when you press the Run button in the code widget.
  • We have provided createFakeData.py and also populated the database with data, so you do not need to worry about that step.

How to see the output: To see the output of your code after making any changes, click the Run button and open the link provided below the code widget in a new browser tab, or switch to the Output tab of the widget. To log in to the Django Admin page, use the following credentials:

  • Username: educative
  • Password: edu1234
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'helloworld.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
Execute all the changes in this code widget.