1

我正在尝试使用__future__ import divisiondjango 进行操作,但它在我的 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'

视图.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

模型.py:

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

product_reviews 是一个查询集。

任何帮助!

4

1 回答 1

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
于 2013-07-21T22:47:33.240 回答