是否可以在从基于类的视图返回的查询集中添加额外值(查询中的2个字段的计算)

问题描述 投票:0回答:2

我试图为从基于类的视图返回的查询添加值。我的Db由用户组成,用户可以有许多交易,而交易可以有很多销售。我想通过((sale.amount_per_coin - sale.transaction.amount_per_coin_sold) * sale.amount)计算出售的利润损失,并将其添加到返回的每一行。是否可以这样做,如果是这样,我将如何去做呢。

交易模型如下

class Transaction(models.Model):
    currency = models.CharField(max_length=20)
    amount = models.IntegerField()
    total_price = models.DecimalField(max_digits=7, 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=7, 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)

下面的销售模型

class Sale(models.Model):
    amount_sold = models.IntegerField()
    total_price_sold = models.DecimalField(max_digits=7, decimal_places=2)
    date_sold = models.DateTimeField(default=timezone.now)
    note = models.TextField(default="")
    transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE)
    amount_per_coin_sold = models.DecimalField(max_digits=7, decimal_places=2, editable=False)

    def save(self, *args, **kwargs):
        self.amount_per_coin_sold = self.total_price_sold / self.amount_sold
        super(Sale, self).save(*args, **kwargs)

基于类的视图如下

class SaleListView(ListView):
    model = Sale
    template_name = 'webapp/sale.html'
    context_object_name = 'sales'
    paginate_by = 5

    def get_queryset(self):
        return super().get_queryset().filter(transaction__owner=self.request.user)

python django
2个回答
0
投票

如果通过将值添加到查询集,则表示该值应该可用于查询集的项目,您可以在Sale上创建一个执行该计算的属性:

@property
def profit_loss(self):
    return (self.amount_per_coin - self.transaction.amount_per_coin_sold) * self.amount

您可以稍后在模板中将其用作{{ sale.profit_loss }}


0
投票

可以使用注释(参见Aggregations):

sales = Sales.objects.filter(
    transaction=transaction      # Filter on the desire transaction.
).annotate(
    profit_lost=(F('amount_per_coin') - F('transaction__amount_per_coin_sold')) * F('amount')
)

现在,您将在proft_lost查询集中为每个sale获取属性sales

© www.soinside.com 2019 - 2024. All rights reserved.