Federico De Marco
Federico De Marco

Reputation: 341

Django, TypeError: unhashable type: 'dict', where is the error?

I'm new in django. I'm trying to run my code but give me the following error: TypeError: unhashable type: 'dict'. I'm checking all code but I don't understand where is the mistake. Moreover I don't sure about the correctness of my code. Could you give me the necessary supports?

Here my models.py

class MaterialeManager(models.Manager):

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).annotate(
            total=F('quantita')*F('prezzo'),
        )

    def get_monthly_totals(self):
        conto = dict((c.id, c) for c in Conto.objects.all())
        return list(
            (conto, datetime.date(year, month, 1), totale)
            for conto_id, year, month, totale in (
                    self.values_list('conto__nome', 'data__year', 'data__month')
                    .annotate(totale=Sum(F('quantita') * F('prezzo')))
                    .values_list('conto__nome', 'data__year', 'data__month', 'totale')
                    ))

class Conto(models.Model):
    nome=models.CharField('Nome Conto', max_length=30, blank=True, default="")
    def __str__(self):
        return  self.nome

class Materiale(models.Model):
    conto = models.ForeignKey(Conto, on_delete=models.CASCADE,)
    tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE,)
    sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True)
    um = models.CharField()
    quantita=models.DecimalField()
    prezzo=models.DecimalField()
    data=models.DateField('Data di acquisto', default="GG/MM/YYYY")
    objects=MaterialeManager()

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

and here my views.py:

def conto_economico(request):
    defaults = list(0 for m in range(12))
    elements = dict()
    for conto, data, totale in Materiale.objects.get_monthly_totals():
        if conto not in elements:
            elements[conto.id] = list(defaults)
        index = data.month - 1  # jan is one, but on index 0
        elements[conto.id][index] = totale

    context= {'elements': elements,}

    return render(request, 'conto_economico/conto_economico.html', context)

Upvotes: 0

Views: 1167

Answers (1)

Sadraoui Taha
Sadraoui Taha

Reputation: 304

You are trying to use a dict:conto as a key to your elements dictionary. That won't work because dictionary keys have to be hashable, which isn't the case. You can use other representative of cont as key, such as its name or id.

Upvotes: 2

Related Questions