Import CSV into Django database

Asked

Viewed 583 times

0

I have a CSV database and wanted to import to my models from Django, 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

Hence 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 correctly import CSV data into my table?

  • Guilherme, There is import/export maybe it could be useful for your problem. See if the link below can be useful. http://abhishekchhibber.com/django-importing-a-csv-file-to-database-models/

  • I tried that and I couldn’t make it work :(

1 answer

0

To work with CSV files I recommend using pyexcel, is quite flexible, besides allowing the use of other formats such as xls and xlsx.

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

If you need to integrate only with CSV, you can still use some plugins like pyexcel-io. Which makes integration with other formats much easier.

In the plugin documentation you will find very practical examples of how it works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.