python - 如何在django中调用 View 文件中的模型函数

标签 python django

我在 model.py 文件中创建了 def 函数,现在我想在 view.py 文件中获取此函数。我知道如何在模板文件中获取此函数,但我不知道如何在 View 文件中获取此函数 例如: 在 model.py 文件中:

 class CartItem(models.Model):
        # cart = models.ForeignKey("Cart")
        cart = models.ForeignKey(
            'Cart',
            on_delete=models.CASCADE,
        )
        product = models.ForeignKey(product_models.Product,on_delete=models.CASCADE)
        item = models.ForeignKey(product_models.ProductDetails,on_delete=models.CASCADE)
        quantity = models.PositiveIntegerField(default=1)

        def __unicode__(self):
            return self.item.title

        @property
        def item_week_real_total(self):
            return self.item.get_week_price() * self.quantity

在view.py文件中

cart_item = CartItem.objects.filter(cart_id=request.session['cart_id'])
        for cart_item_data in cart_item:
            week_total = cart_item_data.item_week_real_total()

但是我收到错误“decimal.Decimal”对象不可调用

最佳答案

item_week_real_total 

应该像属性/属性一样调用,而不是方法。您用 @property 装饰它,因此应该这样调用:

cart_item_data.item_week_real_total

没有()

关于python - 如何在django中调用 View 文件中的模型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56754507/

相关文章:

python - Django 1.9 JSONField 更新行为

python - 迭代已经有索引的变量并写入 JSON

Django:ProgrammingError 关系不存在

python - 反转 '',参数 '' 和关键字参数 '{}' 未找到

django - 使用 drf-yasg,如何提供模式?

python - Python中的Shapefile阅读器?

Python FTPS上传错误: 425 Unable to build data connection: Operation not permitted

Django TastyPie 正确放置嵌套用户模型

python - 将具有各种数字数据类型的结构化数组转换为常规数组

django - 502 错误网关 (nginx/1.10.3 (Ubuntu))