2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DjangoでCSVからモデルに一度でINSERT(import)する方法

Last updated at Posted at 2018-03-21

https://codereview.stackexchange.com/questions/35516/using-a-csv-file-to-insert-data-into-the-django-model

で知りました。bulk createを使うそう(Django 1.4かららしい)

bulk createを使った場合


    def read_user_data(path):
        with open(path) as f:
            reader = csv.reader(f, delimiter=',')
            _header = next(reader)
            User.objects.bulk_create([User(
                id=row[0],
                hoge=row[1],
            ) for row in reader])

forを使った場合


    def read_user_data(self):
        path = self.user_data_path

        with open(path) as f:
            reader = csv.reader(f)
            _header = next(reader)
            for row in reader:
                _, created = User.objects.get_or_create(
                    id=row[0],
                    hoge=row[1],
                )

こんなModel


from django.db import models

class User(models.Model):
    id = models.PositiveIntegerField(primary_key=True)
    hoge = models.CharField(max_length=128)

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?