I try to create a crypto portfolio webpage. My problem is the following. Current Transactions table when i render the html:
| Crypto_Name | Total Trade Value |
|---|---|
| BTC | 150 |
| BTC | 100 |
| DOGE | 200 |
| DOGE | 210 |
Desired Transaction table:
| Crypto_Name | Total Trade Value |
|---|---|
| BTC | 250 |
| DOGE | 410 |
I would like to select distinct values of Crypto_Name and then summarize the values in Total Trade Value.
models.py:
class Transaction(models.Model):
"""Model representing a trade."""
portfolio = models.ForeignKey('Portfolio',on_delete=models.CASCADE)
coin = models.ForeignKey(Coin,on_delete=models.CASCADE)
number_of_coins = models.DecimalField(max_digits=10, decimal_places=0)
trade_price = models.DecimalField(max_digits=10, decimal_places=2)
date = models.DateField()
def __str__(self):
return str(self.portfolio)
@property
def total_trade_value(self):
return self.trade_price * self.number_of_coins
views.py query:
def my_portfolio(request):
filtered_transaction_query_by_user = Transaction.objects.filter(portfolio__user=request.user)
...
What I have tried among many things:
test = filtered_transaction_query_by_user.order_by().values('coin__name').distinct()
It gives me just two crypto name in an ugly format
{'coin__name': 'Bitcoin'}
{'coin__name': 'Doge'}
but the other columns are empty when I render them in the html.
I appreciate your help!!! :)
UPDATE: Big thank to @HudsonBarroso for the answer:
test = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum(trade_price ) * Sum(number_of_coins))).order_by('-total')