Import CSV into the Django database

0

I have a database in CSV and wanted to import into my Django models, CSV has this structure:

  NAME,CLUB,LEAGUE,POSITION,RATING,PACE,SHOOTING,PASSING,DRIBBLING,DEFENDING,PHYSICAL,LOADDATE
  Tore Reginiussen,Rosenborg BK,Tippeligaen,CB,82,65,53,60,68,84,79,2018-04-14 08:37:48

Then I have the following models in the project:

   class Player(models.Model):
        id = models.AutoField(primary_key=True)
        name = models.CharField(max_length=128)
        league = models.ForeignKey('League', on_delete=models.CASCADE)
        club = models.ForeignKey('Club', on_delete=models.CASCADE)
        attributes = models.ForeignKey('Attribute', on_delete=models.CASCADE)

        def __str__(self):
          return self.name

    class League(models.Model):
        name = models.CharField(max_length=30)

        def __str__(self):
          return self.name

    class Club(models.Model):
        name = models.CharField(max_length=30)
        league = models.ForeignKey('League', on_delete=models.CASCADE)

        def __str__(self):
           return self.name

    class Attribute(models.Model):
        pace = models.IntegerField()
        shooting = models.IntegerField()
        passing = models.IntegerField()
        dribbling = models.IntegerField()
        defending = models.IntegerField()
        physical = models.IntegerField()
        position = models.CharField(max_length=4)
        overall = models.IntegerField()

        def __str__(self):
            return '%s %s'%(self.overall, self.position)

What would be the best way to properly import CSV data into my table?

    
asked by anonymous 24.07.2018 / 19:54

1 answer

0

To work with CSV files I recommend using pyexcel , it is very flexible, as well as making it possible to use other formats such as xls and xlsx.

To import the file you must use the get_sheet (which supports any format) method.

If you only need to integrate with CSV, you can still use some plugins like pyexcel-io . It greatly facilitates integration with other formats.

At the plugin documentation you find very practical examples operation.

    
25.07.2018 / 16:19