我正在尝试返回一个用django设置的查询,该查询返回用户进行交易的每种不同货币的购买总金额SUM(amount),支付的总价格SUM(total_price)。这可能吗?建议将不胜感激
下面的交易模型
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)
下面的功能
@login_required
def portfolio(request):
sum_amount = Sum('amount')
sum_total_price = Sum('total_price')
context = {
'transactions': Transaction.objects.filter(owner=request.user).annotate(
current_amount=sum_amount,
purchased_amount=sum_total_price
)
}
return render(request, 'webapp/portfolio.html', context, {'title': 'Portfolio'})
下面的HTML
{% for transaction in transactions %}
<tr>
<td>{{transaction.current_amount}}</td>
<td>{{transaction.purchased_amount}}</td>
</tr>
{% endfor %}
下面的SaleForm
class SaleForm(forms.ModelForm):
amount_sold = forms.IntegerField()
total_price_sold = forms.DecimalField()
date_sold = forms.DateField(
widget=forms.TextInput(
attrs={'type': 'date'}
)
)
note = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Keep a Note?'}))
class Meta:
model = Sale
fields = ('date_sold', 'amount_sold', 'total_price_sold', 'note')
labels = {
'date_sold': _('Sale Date'),
}
help_texts = {
'date_sold': 'Use Calendar to enter date',
}
答案 0 :(得分:1)
在Django ORM中将 GROUP BY 用作
from django.db.models.aggregates import Sum
Transaction.objects.filter(owner=request.user).values('currency').annotate(
sum_amount=Sum('amount'),
sum_total_price=Sum('total_price'))
然后视图变为
from django.db.models.aggregates import Sum
@login_required
def portfolio(request):
context = {
'transactions': Transaction.objects.filter(owner=request.user).values('currency').annotate(
sum_amount=Sum('amount'),
sum_total_price=Sum('total_price'))
}
return render(request, 'webapp/portfolio.html', context, {'title': 'Portfolio'})
答案 1 :(得分:0)
尝试一下
Transaction.objects.filter(owner=request.user).values('currency', 'owner').annotate(amount_sum=Sum('amount'), total_price_sum=Sum('total_price'))
这将返回类似这样的内容
<QuerySet [{'currency': 'BDT', 'owner': 1, 'amount_sum': 123, 'total_price_sum': Decimal('90')}, {'currency': 'USD', 'owner': 1, 'amount_sum': 11, 'total_price_sum': Decimal('30')}]>