【发布时间】:2020-04-25 21:17:15
【问题描述】:
我是 django 的新手。我正在尝试运行我的代码,但出现以下错误:TypeError: unhashable type: 'dict'。
我正在检查所有代码,但我不明白错误在哪里。此外,我不确定我的代码的正确性。你能给我必要的支持吗?
这是我的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)
这里是我的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)
【问题讨论】:
标签: django python-3.x django-models django-forms django-views