Django: Sample data

Sample Data

  • Is helpful when developing
  • Sample data scripts expose issues with data models

Querying in the shell

cd locallibrary
python3 manage.py shell
Enter fullscreen mode
Exit fullscreen mode

The interactive Python environment can be used to create records and query the database.

Import all necessary modules and models for the session.

from catalog.models import Book
Book.objects.all()
Enter fullscreen mode
Exit fullscreen mode

Outputs:

<QuerySet []>`
Enter fullscreen mode
Exit fullscreen mode

An empty query set was returned.

Add a book:

book = Book(title="Python Tutorial")
book.save()
Book.objects.all()
Enter fullscreen mode
Exit fullscreen mode

Outputs:

<QuerySet [<Book: Python Tutorial>]>
Enter fullscreen mode
Exit fullscreen mode

A book was successfully created. Importing everything in the beginning of the shell is painful.

Exit the the shell with exit()

Querying with shell_plus

Navigate to the same directory as requirements.txt.

shell_plus doesn’t come with Django out-of-the-box.

$ pip install django-extensions
Enter fullscreen mode
Exit fullscreen mode

Add the new package to the list of installed packages.

Run pip freeze from the same directory as requirements.txt to update the file. Otherwise, you will create another requirements.txt.

pip freeze > requirements.txt
Enter fullscreen mode
Exit fullscreen mode

Go to settings.py and register the extension in INSTALLED_APPS.

Then, navigate to the locallibrary directory where manage.py is located and run:

python3 manage.py shell_plus
Enter fullscreen mode
Exit fullscreen mode

Now you can query without needing to import models manually.

Sample data script

Install the Faker library and add it to requirements.txt

pip install Faker
pip freeze > requirements.txt
Enter fullscreen mode
Exit fullscreen mode

See create_sample_data.py at https://github.com/Samuel-Lubliner/local-library-django-tutorial/blob/main/locallibrary/create_sample_data.py
Run the sample data script:

python3 create_sample_data.py
Enter fullscreen mode
Exit fullscreen mode

To start querying run python3 manage.py shell_plus


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Uber eats users can schedule orders for delivery from certain restaurants and shops in farmington hills. Us gpu plans.