Problem accessing a specific object field

I’m having trouble trying to access a specific field for a particular object. The object exists, I can access the other fields, but this field is specifically giving an error.

What problem could be happening?

I will show down here the commands I made in the shell so that it is possible to show that the object exists:

import datetime

from django.db import models
from django.utils import timezone

from gcee.models import *

print(CreditosDeEnergia.objects.get(pk=26).ufv)
1424099

print(CreditosDeEnergia.objects.get(pk=26).consumo_local)
1282.0

print(CreditosDeEnergia.objects.get(pk=26).creditos_utilizados)
127,8

print(CreditosDeEnergia.objects.get(pk=26).periodo_data)
Traceback (most recent call last):
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py”, line 172, in get
rel_obj = self.field.get_cached_value(instance)
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/fields/mixins.py”, line 13, in get_cached_value
return instance._state.fields_cache[cache_name]
KeyError: ‘periodo_data’

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/fields/init.py”, line 1772, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not ‘datetime.date’

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File “”, line 1, in
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py”, line 186, in get
rel_obj = self.get_object(instance)
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py”, line 153, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/query.py”, line 404, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/query.py”, line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/query.py”, line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/sql/query.py”, line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/sql/query.py”, line 1373, in _add_q
check_filterable,
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/sql/query.py”, line 1381, in _add_q
check_filterable=check_filterable,
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/sql/query.py”, line 1311, in build_filter
condition = self.build_lookup(lookups, col, value)
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/sql/query.py”, line 1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/lookups.py”, line 22, in init
self.rhs = self.get_prep_lookup()
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/lookups.py”, line 72, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File “/media/ruben.bisneto@ricoli.local/DADOS/RR ENERGIA/SoftwareDB_RR/RR-PowerManager/Test/venv/lib/python3.6/site-packages/django/db/models/fields/init.py”, line 1776, in get_prep_value
) from e
TypeError: Field ‘periodo_id’ expected a number but got datetime.date(2018, 11, 1).

Now here is my gcee.models.py:

from django.db import models
import datetime
from django.utils import timezone

class Clientes(models.Model):
cliente_id = models.AutoField(db_column=‘Cliente_Id’, primary_key=True) # Field name made lowercase.
cliente_nome = models.CharField(db_column=‘Cliente_Nome’, unique=True) # Field name made lowercase.
data_criacao = models.DateField(db_column=‘Data_Criacao’) # Field name made lowercase.
data_modificacao = models.DateField(db_column=‘Data_Modificacao’, blank=True, null=True) # Field name made lowercase.

def __str__(self):
    return self.cliente_nome

class Meta:
    # managed = False
    db_table = 'Clientes'

class ClientesucsRateio(models.Model):
clientesucs_id = models.AutoField(db_column=‘ClientesUCs_Id’, primary_key=True) # Field name made lowercase.
periodo_inicio_vigencia = models.ForeignKey(‘Periodos’, models.DO_NOTHING, db_column=‘Periodo_Inicio_Vigencia’) # Field name made lowercase.
cliente_nome = models.ForeignKey(Clientes, models.DO_NOTHING, db_column=‘Cliente_Nome’) # Field name made lowercase.
perc_da_ger_atrib_para_uc = models.FloatField(db_column=‘Perc_da_ger_atrib_para_UC’) # Field name made lowercase.
uc_destino_numero_de_instalacao = models.ForeignKey(‘Ucs’, models.DO_NOTHING, db_column=‘UC_Destino_Numero_de_Instalacao’) # Field name made lowercase.

def __str__(self):
    return self.cliente_nome

class Meta:
    # managed = False
    db_table = 'ClientesUCs_Rateio'

class Contratos(models.Model):
contrato_id = models.AutoField(db_column=‘Contrato_Id’, primary_key=True) # Field name made lowercase.
contrato_nome = models.CharField(db_column=‘Contrato_Nome’) # Field name made lowercase.
cliente = models.ForeignKey(Clientes, models.DO_NOTHING, db_column=‘Cliente_Id’) # Field name made lowercase.
data_de_criacao = models.DateField(db_column=‘Data_de_criacao’) # Field name made lowercase.
geracao_anual = models.FloatField(db_column=‘Geracao_Anual’) # Field name made lowercase.
valor_mensal = models.FloatField(db_column=‘Valor_Mensal’) # Field name made lowercase.
prazo_do_contrato_anos = models.IntegerField(db_column=‘Prazo_do_Contrato_Anos’) # Field name made lowercase.
aviso_previo_meses = models.IntegerField(db_column=‘Aviso_Previo_Meses’) # Field name made lowercase.
inicio_vigencia = models.ForeignKey(‘Periodos’, models.DO_NOTHING, db_column=‘Inicio_Vigencia’, blank=True, null=True) # Field name made lowercase.

def __str__(self):
    return self.contrato_nome

class Meta:
    # managed = False
    db_table = 'Contratos'

class CreditosDeEnergia(models.Model):
credito_id = models.AutoField(db_column=‘Credito_Id’, primary_key=True) # Field name made lowercase.
periodo_data = models.ForeignKey(‘Periodos’, models.DO_NOTHING, db_column=‘Periodo_Data’) # Field name made lowercase.
cerd_atribuido_ao_periodo = models.ForeignKey(‘Periodos’, models.DO_NOTHING, db_column=‘Cerd_Atribuido_ao_Periodo’) # Field name made lowercase.
ufv = models.ForeignKey(‘Ufv’, models.DO_NOTHING, db_column=‘Ufv_Id’) # Field name made lowercase.
uc_numero_de_instalacao = models.ForeignKey(‘Ucs’, models.DO_NOTHING, db_column=‘UC_Numero_de_instalacao’) # Field name made lowercase.
consumo_leitura_anterior = models.FloatField(db_column=‘Consumo_Leitura_Anterior’, blank=True, null=True) # Field name made lowercase.
consumo_leitura_atual = models.FloatField(db_column=‘Consumo_Leitura_Atual’, blank=True, null=True) # Field name made lowercase.
consumo_local = models.FloatField(db_column=‘Consumo_Local’) # Field name made lowercase.
creditos_atribuidos = models.FloatField(db_column=‘Creditos_Atribuidos’) # Field name made lowercase.
creditos_utilizados = models.FloatField(db_column=‘Creditos_Utilizados’) # Field name made lowercase.
saldo_de_creditos_do_per = models.FloatField(db_column=‘Saldo_de_creditos_do_per’) # Field name made lowercase.
data_expira = models.DateField(db_column=‘Data_Expira’) # Field name made lowercase.

def __str__(self):
    return str(self.saldo_de_creditos_do_per)

class Meta:
    # managed = False
    db_table = 'Creditos_de_Energia'

class GeracaoDeCreditosDeEnergia(models.Model):
geracao_id = models.AutoField(db_column=‘Geracao_Id’, primary_key=True) # Field name made lowercase.
periodo_data = models.ForeignKey(‘Periodos’, models.DO_NOTHING, db_column=‘Periodo_Data’) # Field name made lowercase.
ufv = models.ForeignKey(‘Ufv’, models.DO_NOTHING, db_column=‘Ufv_Id’) # Field name made lowercase.
leitura_anterior = models.FloatField(db_column=‘Leitura_Anterior’) # Field name made lowercase.
leitura_atual = models.FloatField(db_column=‘Leitura_Atual’) # Field name made lowercase.
energia_injetada = models.FloatField(db_column=‘Energia_Injetada’) # Field name made lowercase.

def __str__(self):
    return str(self.ufv)

class Meta:
    # managed = False
    db_table = 'Geracao_de_creditos_de_energia'

class Periodos(models.Model):
periodo_id = models.AutoField(db_column=‘Periodo_Id’, primary_key=True) # Field name made lowercase.
periodo_data = models.DateField(db_column=‘Periodo_Data’, unique=True) # Field name made lowercase.

# def __str__(self):
#     return str(self.periodo_data)

class Meta:
    # managed = False
    db_table = 'Periodos'

class Ucs(models.Model):
numero_de_instalacao = models.AutoField(db_column=‘Numero_de_Instalacao’, primary_key=True) # Field name made lowercase.
uc_titularidade_nome = models.CharField(db_column=‘UC_Titularidade_Nome’) # Field name made lowercase.
uc_titularidade_documento = models.CharField(db_column=‘UC_Titularidade_Documento’) # Field name made lowercase.
uc_conta_contrato = models.IntegerField(db_column=‘UC_Conta_Contrato’, unique=True) # Field name made lowercase.
uc_endereco = models.CharField(db_column=‘UC_Endereco’) # Field name made lowercase.
hc_mes_01 = models.FloatField(db_column=‘HC_Mes_01’) # Field name made lowercase.
hc_mes_02 = models.FloatField(db_column=‘HC_Mes_02’) # Field name made lowercase.
hc_mes_03 = models.FloatField(db_column=‘HC_Mes_03’) # Field name made lowercase.
hc_mes_04 = models.FloatField(db_column=‘HC_Mes_04’) # Field name made lowercase.
hc_mes_05 = models.FloatField(db_column=‘HC_Mes_05’) # Field name made lowercase.
hc_mes_06 = models.FloatField(db_column=‘HC_Mes_06’) # Field name made lowercase.
hc_mes_07 = models.FloatField(db_column=‘HC_Mes_07’) # Field name made lowercase.
hc_mes_08 = models.FloatField(db_column=‘HC_Mes_08’) # Field name made lowercase.
hc_mes_09 = models.FloatField(db_column=‘HC_Mes_09’) # Field name made lowercase.
hc_mes_10 = models.FloatField(db_column=‘HC_Mes_10’) # Field name made lowercase.
hc_mes_11 = models.FloatField(db_column=‘HC_Mes_11’) # Field name made lowercase.
hc_mes_12 = models.FloatField(db_column=‘HC_Mes_12’) # Field name made lowercase.
conta_minima = models.FloatField(db_column=‘Conta_Minima’, blank=True, null=True) # Field name made lowercase.

def __str__(self):
    return str(self.numero_de_instalacao)

class Meta:
    # managed = False
    db_table = 'UCs'

class Ufv(models.Model):
ufv_id = models.AutoField(db_column=‘Ufv_Id’, primary_key=True) # Field name made lowercase.
ufv_numero_de_instalacao = models.ForeignKey(Ucs, models.DO_NOTHING, db_column=‘Ufv_Numero_de_Instalacao’) # Field name made lowercase.
data_de_ligacao = models.DateField(db_column=‘Data_de_Ligacao’) # Field name made lowercase.
prioritario_abater_consumo_local = models.BooleanField(db_column=‘Prioritario_Abater_Consumo_Local’) # Field name made lowercase.
prazo_validade_creditos_gerados_meses = models.FloatField(db_column=‘Prazo_Validade_Creditos_Gerados_Meses’) # Field name made lowercase.
gp_mes_01 = models.FloatField(db_column=‘GP_Mes_01’) # Field name made lowercase.
gp_mes_02 = models.FloatField(db_column=‘GP_Mes_02’) # Field name made lowercase.
gp_mes_03 = models.FloatField(db_column=‘GP_Mes_03’) # Field name made lowercase.
gp_mes_04 = models.FloatField(db_column=‘GP_Mes_04’) # Field name made lowercase.
gp_mes_05 = models.FloatField(db_column=‘GP_Mes_05’) # Field name made lowercase.
gp_mes_06 = models.FloatField(db_column=‘GP_Mes_06’) # Field name made lowercase.
gp_mes_07 = models.FloatField(db_column=‘GP_Mes_07’) # Field name made lowercase.
gp_mes_08 = models.FloatField(db_column=‘GP_Mes_08’) # Field name made lowercase.
gp_mes_09 = models.FloatField(db_column=‘GP_Mes_09’) # Field name made lowercase.
gp_mes_10 = models.FloatField(db_column=‘GP_Mes_10’) # Field name made lowercase.
gp_mes_11 = models.FloatField(db_column=‘GP_Mes_11’) # Field name made lowercase.
gp_mes_12 = models.FloatField(db_column=‘GP_Mes_12’) # Field name made lowercase.

def __str__(self):
    return str(self.ufv_numero_de_instalacao)

class Meta:
    # managed = False
    db_table = 'Ufv'

class Ufvclientes(models.Model):
ufvcliente_id = models.AutoField(db_column=‘UfvCliente_Id’, primary_key=True) # Field name made lowercase.
periodo_inicio_vigencia = models.ForeignKey(Periodos, models.DO_NOTHING, db_column=‘Periodo_Inicio_Vigencia’) # Field name made lowercase.
ufv = models.ForeignKey(Ufv, models.DO_NOTHING, db_column=‘Ufv_Id’) # Field name made lowercase.
cliente_nome = models.ForeignKey(Clientes, models.DO_NOTHING, db_column=‘Cliente_Nome’) # Field name made lowercase.
perc_da_ger_atrib_para_cliente = models.FloatField(db_column=‘Perc_da_ger_atrib_para_cliente’) # Field name made lowercase.

def __str__(self):
    return str(self.ufv)

class Meta:
    # managed = False
    db_table = 'UfvClientes'

class Ufvucs(models.Model):
ufvucs_id = models.AutoField(db_column=‘UfvUCs_Id’, primary_key=True) # Field name made lowercase.
periodo_inicio_vigencia = models.ForeignKey(Periodos, models.DO_NOTHING, db_column=‘Periodo_Inicio_Vigencia’) # Field name made lowercase.
ufv = models.ForeignKey(Ufv, models.DO_NOTHING, db_column=‘Ufv_Id’) # Field name made lowercase.
uc_destino_numero_de_instalacao = models.ForeignKey(Ucs, models.DO_NOTHING, db_column=‘UC_Destino_Numero_de_Instalacao’) # Field name made lowercase.
perc_da_ger_atrib_para_uc = models.FloatField(db_column=‘Perc_da_ger_atrib_para_UC’) # Field name made lowercase.

def __str__(self):
    return str(self.ufv)

class Meta:
    # managed = False
    db_table = 'UfvUCs'

Which database are you using?

First reaction is that there’s some sort of mismatch between your model and the database itself.

It might be worth checking to see the SQL definition for the Periodos model.

Specifically, I suggest verifying that the periodo_id column in the Periodos table is actually an integer and that periodo_data is a date field.

I’m using SQLite DB and used sqlitstudio do create those tables. Then I used inspectdb to create the models.

Here is my sql codes for the table “Periodos”:

CREATE TABLE Periodos (
Periodo_Id INTEGER PRIMARY KEY ASC AUTOINCREMENT
NOT NULL,
Periodo_Data DATE UNIQUE
NOT NULL
);

And here is the models code for “Periodos”:

class Periodos(models.Model):
periodo_id = models.AutoField(db_column=‘Periodo_Id’, primary_key=True) # Field name made lowercase.
periodo_data = models.DateField(db_column=‘Periodo_Data’, unique=True) # Field name made lowercase.

I can’t find where is the problem…

I can also access the Periodos table as we can see:

print(Periodos.objects.get(pk=1))
Periodos object (1)

print(Periodos.objects.all())
<QuerySet [<Periodos: Periodos object (1)>, <Periodos: Periodos object (2)>, <Periodos: Periodos object (3)>, <Periodos: Periodos object (4)>, <Periodos: Periodos object (5)>, <Periodos: Periodos object (6)>, <Periodos: Periodos object (7)>, <Periodos: Periodos object (8)>, <Periodos: Periodos object (9)>, <Periodos: Periodos object (10)>, <Periodos: Periodos object (11)>, <Periodos: Periodos object (12)>, <Periodos: Periodos object (13)>, <Periodos: Periodos object (14)>, <Periodos: Periodos object (15)>, <Periodos: Periodos object (16)>, <Periodos: Periodos object (17)>, <Periodos: Periodos object (18)>, <Periodos: Periodos object (19)>, <Periodos: Periodos object (20)>, ‘…(remaining elements truncated)…’]>

print(Periodos.objects.get(pk=1).periodo_id)
1

print(Periodos.objects.get(pk=1).periodo_data)
2018-02-01

Does

CreditosDeEnergia.objects.get(pk=26).periodo_data

work for any valid value for pk in CreditosDeEnergia? Also, what’s the SQL definition for that table?

can you do a:

select periodo_data from creditos_de_energia where credito_id=26;

on your table? It seems like you may have a data error in the creditos_de_energia table.

Hello Ken.

CreditosDeEnergia.objects.get(pk=26) ----- It doesn’t work with any valid pk.

Here is the table SQL code:

CREATE TABLE Creditos_de_Energia (
Credito_Id INTEGER PRIMARY KEY ASC AUTOINCREMENT
NOT NULL,
Periodo_Data DATE NOT NULL
REFERENCES Periodos (Periodo_Data),
Cerd_Atribuido_ao_Periodo DATE REFERENCES Periodos (Periodo_Data),
Ufv_Id INTEGER REFERENCES Ufv (Ufv_Id)
NOT NULL,
UC_Numero_de_instalacao INTEGER REFERENCES UCs (Numero_de_Instalacao)
NOT NULL,
Consumo_Leitura_Anterior REAL,
Consumo_Leitura_Atual REAL,
Consumo_Local REAL NOT NULL,
Creditos_Atribuidos REAL NOT NULL,
Creditos_Utilizados REAL NOT NULL,
Saldo_de_creditos_do_per REAL NOT NULL,
Data_Expira DATE NOT NULL
);

Here the output from sql query:

sqlite> .open rrpm.db
sqlite> .tables
Clientes Periodos
ClientesUCs_Rateio UCs
Contratos Ufv
Creditos_de_Energia UfvClientes
Geracao_de_creditos_de_energia UfvUCs
sqlite>
sqlite>
sqlite>
sqlite> select Periodo_Data from Creditos_de_Energia where Credito_Id=26;
2018-11-01
sqlite>

“It seems like you may have a data error in the creditos_de_energia table” - I’ve looked it all… can’t find it! I’m sending a picture of the table data. I’m using sqlitesutio browser.

That is your problem.

Your model (extract) ->

class CreditosDeEnergia(models.Model):
    credito_id = models.AutoField(db_column=‘Credito_Id’, primary_key=True) # Field name made lowercase.
    periodo_data = models.ForeignKey(‘Periodos’, models.DO_NOTHING, db_column=‘Periodo_Data’) # Field name made lowercase.

Notice that periodo_data is defined in your model as a ForeignKey to Periodos. That means that the column in your Creditos_de_energia model must be the corresponding primary key in the Periodos table. Periodos defines its primary key as being an integer field.

However, what you have in your table are dates. That’s wrong. They need to be the integers corresponding to the proper periodo_id of the Periodos table.

Ken

Thank you very much Ken!

I’m going to read more about db normalization. I’m learning how to code…