使用方法:从__future__导入分区用django

时间:2013-07-21 19:35:48

标签: django django-templates

我正在尝试将__future__ import division与django一起用于我的操作,但它在我的views.py中无效。

在django shell下与python shell完全相同:

>>> from __future__ import division
>>> result = 37 / 3
>>> result
12.333333333333334
>>> 

当我尝试使用它时,django views.py中的相同内容不起作用。

error message: unsupported operand type(s) for /: 'int' and 'instancemethod'

views.py:

from __future__ import division

def show_product(request, product_slug, template_name="product.html"):
    review_total_final = decimal.Decimal('0.0')
    review_total = 0
    product_count = product_reviews.count # the number of product rated occurences
    if product_count == 0:
        return review_total_final
    else:
        for product_torate in product_reviews:
            review_total += product_torate.rating
            review_total_final = review_total / product_count
            return review_total_final
    return review_total_final

models.py:

class ProductReview(models.Model):
    RATINGS =((5,5),.....,)
    product = models.ForeignKey(Product)
    rating = models.PositiveSmallIntegerField(default=5, choices=RATINGS)
    content = models.TextField()

product_reviews是一个查询集。

任何帮助!!!

1 个答案:

答案 0 :(得分:2)

from __future__ import division与此无关;你试图通过方法本身划分一个值,而不是先调用方法来获得一个合适的操作数。比较和对比:

>>> class X(object):
...   def count(self):
...     return 1
... 
>>> x = X()
>>> 1 / x.count
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'int' and 'instancemethod'
>>> 1 / x.count()
1