Menu Close

How to import csv data into Python Django models?

To import csv data into Python Django models, we can call csv.reader.

For instance, we write

with open(path) as f:
        reader = csv.reader(f)
        for row in reader:
            _, created = Teacher.objects.get_or_create(
                first_name=row[0],
                last_name=row[1],
                middle_name=row[2],
                )

to open the file at path with open.

Then we call csv.reader with file f.

And then we loop through the rows and call the get_or_create method to create items that don’t exist in the database from the rows.

Posted in Python, Python Answers