我可以总结注释中的属性吗?

时间:2019-04-27 16:33:43

标签: django database orm sum

我正在我的项目中创建一个html表,该表由数据库中的一些求和值填充,我试图求和(coins_remaining),这是我的数据库模型的一个属性。通过从sum_amount_sold表的Sale中减去amount表的Transaction来计算Coins_remaining。这可能吗?如果可以的话,我该怎么办?

下面的HTML表格

           {% for transaction in transactions %}
            <tr>
                <td>{{transaction.currency}}</td>
                <td>{{transaction.sum_amount_purchased}}</td>                
                <td>{{transaction.sum_total_price_purchased}}</td>
                <td>{{transaction.sum_total_price_purchased}}</td>
            </tr>
            {% endfor %}

下面的功能

@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_current=?

    }
    return render(request, 'webapp/portfolio.html', context, {'title': 'Portfolio'})

下面的交易模型

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 coins_remaining(self):
        return self.amount - sum(self.sales.all().values_list('amount_sold', flat=True))

下面的销售模式

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})

1 个答案:

答案 0 :(得分:1)

您可以为此使用Subquery注意:您必须使用OuterRef来获取正确的Transaction。无法真正尝试使用它,但这是您可以使用Subquery注释查询集并在以后的计算中使用它的方法。我不确定是否能解决您的问题,但是您可以:

coins_remaining_query = (
    Sale.objects.filter(transaction=OuterRef("id"))
    .annotate(coins_remaining=Sum("amount_sold"))
    .values("coins_remaining")
)

Transaction.objects.filter(owner=request.user).values("currency").annotate(
    sum_amount_purchased=Sum("amount"),
    sum_total_price_purchased=Sum("total_price"),
    coins_remaining=Subquery(coins_remaining_query)
).annotate(sum_amount_current=F("sum_amount_purchased")-F("coins_remaining"))