The comma-separated values (CSV) format is probably the simplest way to store tabular data in a text file. In this recipe, we will create a management command that imports data from CSV to a Django database. We will need a CSV list of movies with a title, URL, and release year. You can easily create such files with Excel, Calc, or another spreadsheet application.
Create a movies
app with the Movie
model containing the following fields: title
, url
, and release_year
. Place the app under INSTALLED_APPS
in the settings.
Follow these steps to create and use a management command that imports movies from a local CSV file:
In the
movies
app, create amanagement
directory and then acommands
directory in the newmanagement
directory. Put the empty__init__.py
files in both new directories to make them Python packages.Add an
import_movies_from_csv.py
file there with the following content:# movies/management/commands/import_movies_from_csv...