【发布时间】:2020-08-08 23:21:13
【问题描述】:
我有以下模型结构:
Product | Price | Quantity | Total* | Date of purchase
Product A | 10 | 1 | 10 | 1/01/2020
Product B | 10 | 2 | 20 | 1/02/2020
*totale 是使用 models.py 中的管理器函数创建的。
我想在我的项目的另一个应用程序中获得每种产品每个月的总和。 像这样的:
Product | Gen | Feb | Mar | Apr | May | Jun | ....
Product A | 10 | 0 | 0 | 0 | 0 | 0 | ....
Product A | 0 | 20 | 0 | 0 | 0 | 0 | ....
这是我的models.py
class Product(models.Model):
nome= models.CharField()
class MaterialeManager(models.Manager):
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).annotate(
total=F('quantity')*F('price'),
)
def get_monthly_totals(self):
products = dict((p.id, p) for p in Products.objects.all())
return list(
(product, datetime.date(year, month, 1), totale)
for product_id, year, month, totale in (
self.values_list('product__nome', 'date__year', 'date__month')
.annotate(totale=Sum(F('quantity') * F('price')))
.values_list('product__nome', 'date__year', 'date__month', 'totale')
)
class Materiale(models.Model):
product= models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
quantity=models.DecimalField()
price=models.DecimalField()
date=models.DateField()
obejcts=MaterialManager()
但我尝试以下代码来弄清楚但不起作用:
views.py
def conto_economico(request):
elements = Materiale.objects.all()
context= {
'elements':elements,
}
return render(request, 'conto_economico/conto_economico.html', context)
模板.html
{% for e in elements %}
{{e.totale}}
{% endfor %}
【问题讨论】:
标签: django django-models django-rest-framework django-forms django-views