Django csv error

Asked

Viewed 46 times

1

Well, I have a problem reading csv and entering the data. I believe it is in 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 mistake is:

Cannot assign "'110001'": "Aih.idmunicipio" must be a "Municipios" instance.

1 answer

1


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

You have two options, overriding the code below:

t.idmunicipio = row[0]

For:

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 it is requested.

  • Buddy, it worked...just by putting the t.idmunicipio_id = row[0]. Thank you very much friend!!!! To starting now with python, thank you very much indeed!

  • Cool, I’ve already acquired a certain experience with Python. If you need.

Browser other questions tagged

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