Я хочу создать другой контекст для отправки другого набора запросов в HTML. Я хочу отправить сумму всех общих продаж из модели транзакций в HTML. Возможно ли это, и если да, то как мне поступить?
Вид ниже
@login_required
def portfolio(request):
context = {
'transactions': Transaction.objects.filter(owner=request.user).values('currency').annotate(
sum_amount_purchased=Sum('amount'),
sum_total_price_purchased=Sum('total_price'),
sum_amount_sold=Sum('sales__amount_sold'),
sum_amount_current=F("sum_amount_purchased") - F("sum_amount_sold"),
avg_amount_per_coin=Avg("amount_per_coin"),
sum_total_price_current=ExpressionWrapper(F("sum_amount_current")*F("avg_amount_per_coin"),
output_field=DecimalField()),
sum_total_income=Sum('sales__total_price_sold'),
sum_profit_loss=F("sum_total_price_current") + F("sum_total_income") - F("sum_total_price_purchased"),
),
'totals': Transaction.objects.filter(owner=request.user).annotate(
total_spends=Sum('total_price'))
}
return render(request, 'webapp/portfolio.html', context, {'title': 'Portfolio'})
HTML ниже
<div class = "col-md-6">
{% for total in totals %}
<h1> Total Spent: {{ total.total_spends }}</h1>
{% endfor %}
</div>
Модель транзакции ниже
class Transaction(models.Model):
currency = models.CharField(max_length=20)
amount = models.IntegerField()
total_price = models.DecimalField(max_digits=8, decimal_places=2)
date_purchased = models.DateTimeField()
note = models.TextField(default="")
owner = models.ForeignKey(User, on_delete=models.CASCADE)
amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False)
def save(self, *args, **kwargs):
self.amount_per_coin = self.total_price / self.amount
super(Transaction, self).save(*args, **kwargs)
def __str__(self):
return str(self.pk)+','+self.currency + ', '+str(self.amount)
def get_absolute_url(self):
return reverse('transaction-detail', kwargs={'pk': self.pk})
Продажа модели ниже
class Sale(models.Model):
amount_sold = models.IntegerField()
total_price_sold = models.DecimalField(max_digits=8, decimal_places=2)
date_sold = models.DateTimeField(default=timezone.now)
note = models.TextField(default="")
transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="sales")
amount_per_coin_sold = models.DecimalField(max_digits=8, decimal_places=2, editable=False)
def __str__(self):
return str(self.pk)+','+str(self.amount_sold) + ', '+self.note
def save(self, *args, **kwargs):
self.amount_per_coin_sold = self.total_price_sold / self.amount_sold
super(Sale, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('sale-detail', kwargs={'pk': self.pk})