没有得到django模板中的值

时间:2017-01-27 19:37:20

标签: django

models.py

class Stock(models.Model):
  name = models.CharField(verbose_name='Name of Stock', max_length=300)
  purchase_price = models.DecimalField(verbose_name='Purchase Price', blank=True, null=True, max_digits=30, decimal_places=2)
  pre_price = models.DecimalField(verbose_name='Last Day Price', blank=True, null=True, max_digits=30, decimal_places=2)
  current_price = models.DecimalField(verbose_name='Current Price', blank=True, null=True, max_digits=30, decimal_places=2)

def __str__(self):
    return self.name

class StockList(models.Model):
  user = models.ForeignKey(settings.AUTH_USER_MODEL)
  stock = models.ForeignKey(Stock)
  quantity = models.IntegerField(verbose_name='No.of Shares',default=0)
  timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)

  def __str__(self):
      return str(self.stock)

def market_value_reciever(sender, instance, *args, **kwargs):
  purchase_price = instance.stock.purchase_price
  quantity = instance.quantity
  market_value = purchase_price * quantity
  instance.market_value = market_value
  print(purchase_price)
  print(market_value)

pre_save.connect(market_value_reciever, sender=StockList)

html模板

        {% for item in queryset %}
        <tr>
            <td>
              <a href="#">{{ item.stock.name }}</a>
            </td>
             <td>
              {{ item.purchase_price }}
            </td>
             <td>
              {{ item.quantity }}
            </td>
            <td>
              {{ item.market_value }}
            </td>


        </tr>
   {% endfor %}

这里我只得到html模板上的数量值,购买价格和市场价值字段没有上模板,但它的值正在终端上。任何人都可以提供帮助,非常感谢你。

1 个答案:

答案 0 :(得分:0)

您可以在StockList模型中使用@property装饰器,因此模板可以渲染它:

class StockList(models.Model):

    @property
    def purchase_price(self):
        return self.stock.purchase_price

    @property
    def market_value(self):
        return self.purchase_price * self.quantity