我对此问题"conversion from method to Decimal is not supported django" error有点儿困惑,在其中添加()会给我一个错误'DeferredAttribute' object is not callable
,删除它们会给我一个conversion from DeferredAttribute to Decimal is not supported
(我当前的错误是下面的代码)
我的目标是两个拿我的3个值,弄清楚什么是盈亏:
Profit_long =(价格1-价格2)*大小
*我不太确定数学语法是否正确,因为上述错误消息不会让我走那么远。根据我所读的内容,只要这些变量是整数,数学语法就应该正确。不确定是否可以使用小数。那是第二步。首先,我需要解决以上问题。
views.py
class TradeDetailView(DetailView):
template_name = 'tj/cp/trade/detail.html'
queryset = Trade.objects.all()
def get_object(self):
id_ = self.kwargs.get("id")
return get_object_or_404(Trade, id=id_)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
entry_price = Decimal(Trade.entry_price)
exit_price = Decimal(Trade.entry_price)
size = Decimal(Trade.size)
context['profit_long'] = (entry_price - exit_price) * size
return context
models.py
class Trade(models.Model):
...
size = models.DecimalField(null=True, blank=True, max_digits=50, decimal_places=2)
entry_price = models.DecimalField(null=True, blank=True, max_digits=50, decimal_places=2)
exit_price = models.DecimalField(null=True, blank=True, max_digits=50, decimal_places=2)
...
答案 0 :(得分:1)
为了您的正常工作,我修改了您的代码:
class TradeDetailView(DetailView):
template_name = 'tj/cp/trade/detail.html'
pk_url_kwarg = 'id'
model = Trade
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
entry_price = Decimal(self.object.entry_price)
exit_price = Decimal(self.object.exit_price)
size = Decimal(self.object.size)
context['profit_long'] = (entry_price - exit_price) * size
return context
但是最好做不同的事情。为模型交易添加属性:
class Trade(models.Model):
# ...
size = models.DecimalField(null=True, blank=True, max_digits=50, decimal_places=2)
entry_price = models.DecimalField(null=True, blank=True, max_digits=50, decimal_places=2)
exit_price = models.DecimalField(null=True, blank=True, max_digits=50, decimal_places=2)
# ...
@property
def profit_long(self):
return (self.entry_price - self.exit_price) * self.size
然后视图将变得更加简洁。
class TradeDetailView(DetailView):
template_name = 'tj/cp/trade/detail.html'
pk_url_kwarg = 'id'
model = Trade
context_object_name = 'trade'
并在Django模板中使用属性:
<p>Profit long: {{ trade.profit_long }}</p>