Alternative Methods to Populating your Django Database
A practical guide to populating Django database’s
Traditionally when working with django in order to populate our database we normally have to log into the admin panel. But have you ever wondered about other alternative methods of performing this same functionality in a more convenient and time saving manner, if so then this blog post is for you.
This will be a three part series in which I will teach you how to populate your Django database using,
- Fixtures
- Migrations
- 3rd party packages
Assumptions being made
If you are reading this blog post, I am assuming you already know the basics of Django such as ;
- How to setup a Django project
With the above assumption being made, lets dive into the first part of our tutorial series
Fixtures
A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you’ve already got some data is to use the
python manage.py dumpdata
Fixtures can be written as JSON, XML or YAML (with PyYAML installed) documents but for this tutorial we shall use JSON as it’s a lot more common and easier to work with.
Loading Data from your fixtures
In order to load data from fixtures you run,
python manage.py loaddata <fixturename>
Where Django finds fixture files
By default, Django looks in the fixtures
directory inside each app for fixtures. You can set the FIXTURES_DIRS setting to a list of additional directories where Django should look.
When running manage.py loaddata, you can also specify a path to a fixture file, which overrides searching the usual directories.
Practical Implementation
for this I have created a basic app and inside of our app directory we can see a fixtures directory which contains a a file named schools.json as seen below which will be use to populate our models.
Our models.py file contains the following which will be populated using the fixtures above .
After we run
python manage.py loaddata schools.json
we observe our database has been populated with the information contained in the schools.json file
Conclusion
These brings us to the end of the first part of this tutorial series and I hope you the reader can now move ahead and try implementing this in your projects.
The second part of this series will be focused on how we can use migrations to perform same functionality.
Resources