Я пытаюсь создать контекст для рендеринга в HTML-таблицу.Я хочу заполнить таблицу названием каждой валюты, которую купил пользователь, общей текущей суммой, принадлежащей этой валюте, общей суммой покупки, общей суммой продажи, общей текущей стоимостью указанной валюты, общей стоимостью покупки и общей стоимостью продажи.Я действительно изо всех сил пытаюсь сделать это возможно?и если да, то могу ли я получить совет о том, как
Функция ниже
def portfolio(request):
count = Transaction.objects.filter(owner=request.user).values('currency').distinct(),count
context = {
}
return render(request, 'webapp/portfolio.html', context, {'title': 'Portfolio'})
Html Таблица ниже
<table class="table">
<thead>
<tr>
<th scope="col">Coin</th>
<th scope="col">Current</th>
<th scope="col">Purchased</th>
<th scope="col">Sold</th>
<th scope="col">Current Value</th>
<th scope="col">Purchased Value</th>
<th scope="col">Sold Value</th>
</tr>
</thead>
<tbody>
{% for total_transaction in total_transaction %}
<tr>
<td>{{total_transaction.currency}}</td>
<td>{{total_transaction.current_amount}}</td>
<td>{{total_transaction.purchased_amount}}</td>
<td>{{total_transaction.sold_amount}}</td>
<td>{{total_transaction.current_value}}</td>
<td>{{total_transaction.purchased_value}}</td>
<td>{{total_transaction.sold_value}}</td>
</tr>
{% endfor %}
</tbody>
</table>
Модель транзакции ниже
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})
@property
def coin_value(self):
try:
current_price = requests.get("https://min-api.cryptocompare.com/data/price?fsym="+self.currency+"&tsyms=EUR")
price = json.loads(current_price.content)
return price["EUR"]
except:
return 0
@property
def total_value(self):
value = self.coin_value * self.amount
return round(value, 2)
@property
def profit_loss(self):
value = float(self.total_value) - float(self.total_price)
return round(value, 2)
@property
def profit_loss_percent(self):
value = ((float(self.total_value) - float(self.total_price))/self.total_value)*100
return round(value, 1)
Продажа модели ниже
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})
@property
def profit_loss(self):
return (self.amount_per_coin_sold - self.transaction.amount_per_coin) * self.amount_sold
@property
def profit_loss_percent(self):
value = ((self.total_price_sold - (self.transaction.amount_per_coin * self.amount_sold))/self.total_price_sold) * 100
return round(value, 1)
```