Categories
Python Answers

How to import csv data into Python Django models?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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