将CSV文件导入Django模型

时间:2018-07-25 00:12:49

标签: python django database csv model

我有一个CSV文件,我想将此文件的内容导入到我的Django模型中,有人可以帮我解释一下我该怎么做吗?

这是我的CSV。

NAME,CLUB,LEAGUE,POSITION,RATING,PACE,SHOOTING,PASSING,DRIBBLING,DEFENDING,PHYSICAL,LOADDATE
Aleksandar Kolarov,Roma,Calcio A,LB,81,72,68,72,64,84,85,2018-04-14 08:37:48

我的模特是

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)

1 个答案:

答案 0 :(得分:1)

如果要在django admin中执行此操作,可以按照以下步骤操作:

1.install

library(matlabr)
if(have_matlab())
{ get_matlab(try_defaults = TRUE, desktop = FALSE, splash = FALSE, display = FALSE, wait = TRUE}

while (t < total.year ) {            # my R script runs over multiple years
  # pre-calculations
  ...
  <<change-some-files.txt>>         # these are later used by the matlab script
  ... 
  # run matlab
  system("matlab -wait -nodesktop -nosplash -nodisplay -r \"run('<<here-the-full-path-name-of-the-matlap-script.m>>'); exit\"")
}

2.update settings.py文件

pip install django-import-export

3。将此添加到admin.py文件中

INSTALLED_APPS = (    
    'import_export',
)