Error Django csv

0

Well, I'm having a problem reading csv and entering the data. I believe it's in the foreign key. The code is:

View:

def csvAih(request):
        coluna = 1
        mes = 1
        ano = 2008
        while (ano < 2017):
            with open('local', 'rb') as csvfile:
                spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
                for row in spamreader:
                    if row[0] is not None:
                        t = Aih()
                        t.idmunicipio = row[0]
                        t.quantidade = row[coluna]
                        t.data = str(ano) + '-' + str(mes) + '-01'
                        t.save(force_insert=True)
                        print t.idmunicipio, t.data, t.quantidade
            mes = mes + 1
            coluna = coluna + 1
            print mes
            if (coluna-1)%12 == 0:
                print ano
                mes = 1
                ano = ano + 1

class Municipios(models.Model):
    idmunicipio = models.IntegerField(db_column='idMunicipio', primary_key=True)  # Field name made lowercase.
    nome = models.CharField(max_length=45, blank=True, null=True)
    uf = models.ForeignKey(Estados)
    latitude = models.CharField(max_length=45, blank=True, null=True)
    longitude = models.CharField(max_length=45, blank=True, null=True)
    idestado = models.IntegerField(db_column='idEstado')  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'municipios'

Models:

class Aih(models.Model):
    quantidade = models.IntegerField()
    idmunicipio = models.ForeignKey(Municipios, to_field='idmunicipio',  db_column='idMunicipio')  
    data = models.DateField(primary_key=True)

And the error is:

  

Can not assign "'110001'": "Aih.idmunicipio" must be a "Municipalities"   instance.

    
asked by anonymous 13.09.2016 / 00:48

1 answer

1

The problem is that you are assigning the id to the idmunicipio attribute. In django, it expects you to assign an instance, in this case, of Municipios .

You have two options, replacing the code below:

t.idmunicipio = row[0]

By:

t.idmunicipio_id = row[0]

Or:

t.idmunicipio = Municipios.objects.get(pk=row[0])

In the first option you directly assign the id of the foreign key. In the second, you assign the instance as requested.

    
13.09.2016 / 20:36