Django从所有对象获取函数结果之和

2024-09-30 01:34:13 发布

您现在位置:Python中文网/ 问答频道 /正文

有些东西告诉我这个问题很明显,但我一直坚持下去,因为我所做的所有搜索基本上都是以计算所有对象的总和结束的,这就是上下文['all_trades']所做的。但是,我希望计算函数中计算的所有对象结果的总和。我希望措辞恰当

如果我打印出上下文,结果如下:

{'view': <portfolios.views.StatsView object at 0x0000020CC8B0D188>, 'all_trades': 13, 'gross_profit': <function Trade.get_profit_loss_value at 0x0000020CC70598B8>}

models.py

class Trade(models.Model):
    class Meta:
        verbose_name = "Trade"
        verbose_name_plural = "Trades"

    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    ...

    # P/L Value = Sum of all buys * ( Entry Cost Per Unit (CPU) - Exit Cost Per Unit (CPU) )
    def get_profit_loss_value_or_None(self):
        if self.get_exit_cpu() > 0:
            if self.type == 'Long':
                result = self.get_entries().aggregate(
                get_profit_loss_value=Sum('amount', output_field=models.FloatField()
                                           ) * (self.get_exit_cpu() - self.get_entry_cpu()))['get_profit_loss_value']
            return 0 if result is None else result
        elif self.type == 'Short':
            result = self.get_entries().aggregate(
            get_profit_loss_value=Sum('amount', output_field=models.FloatField()
                                           ) * -1 * (self.get_exit_cpu() - self.get_entry_cpu()))['get_profit_loss_value']
            return 0 if result is None else result
        else:
            return 0

    def get_profit_loss_value(self):
        ret = self.get_profit_loss_value_or_None()
        return 0 if ret is None else ret

views.py

class StatsView(TemplateView):
    template_name = 'dashboard/stats.html'

    def get_context_data(self, *args, **kwargs):
        context = super(StatsView, self).get_context_data(*args, **kwargs)
        # get # of trades user made
        context['all_trades'] = Trade.objects.filter(user=self.request.user).count()
        # get sum of all trades profit/loss
        context['gross_profit'] = Trade.get_profit_loss_value 
        return context

根据Dean Elliott到目前为止的回答,我们对views.py进行了调整

class StatsView(TemplateView):
    template_name = 'dashboard/stats.html'

    def get_context_data(self, *args, **kwargs):
        trade = Trade.objects.filter(user=self.request.user)
        context = super(StatsView, self).get_context_data(*args, **kwargs)
        context['all_trades'] = Trade.objects.filter(user=self.request.user).count()
        context['gross_profit'] = trade.get_profit_loss_value()
        #context['net_profit'] = Trade.objects.filter(user=self.request.user).count()
        print(context['gross_profit'])
        return context

错误结果:

line 352, in get_context_data
    context['gross_profit'] = trade.get_profit_loss_value()
AttributeError: 'QuerySet' object has no attribute 'get_profit_loss_value'

Tags: selfgetreturnvaluemodelscontextresultall
2条回答

看起来context['gross_profit'] = Trade.get_profit_loss_value需要一个Trade对象。例如trade = Trade.objects.get(id=1),然后使用trade.get_profit_loss_value()

一定要添加括号以及!没有括号,您只是引用函数,而不是实际调用它

get_context_data()方法中获取trade时,必须使用get()方法而不是filter(),如下所示

def get_context_data(self, *args, **kwargs):
    trade = Trade.objects.get(user=self.request.user)

而不是

def get_context_data(self, *args, **kwargs):
    trade = Trade.objects.filter(user=self.request.user)

如果您想使用filter(),那么使用first()从中获取单个对象,如下所示

def get_context_data(self, *args, **kwargs):
    trade = Trade.objects.filter(user=self.request.user)
    ... YOUR LOGIC ...
    profit_loss = sum([t.get_profit_loss_value() for t in trade])
    context['gross_profit'] = profit_loss
    ... YOUR LOGIC ...        

因此,它将为您提供来自queryset的第一个元素

相关问题 更多 >

    热门问题