Skip to main content
 首页 » 编程设计

python之如何计算元素的值(value)

2025年05月04日51mate10pro

我已经创建了商店。我有两个模型:

我的模型:

class Product(models.Model): 
    name = models.CharField(verbose_name="name", max_length=40) 
    cost = models.FloatField(verbose_name="price") 
 
    def __unicode__(self): 
        return self.name 
 
class Shop(models.Model): 
    product = models.ManyToManyField(Product) 
    name = models.CharField(verbose_name="Nazwa", max_length=40) 
    budget = models.FloatField(verbose_name="kwota") 
 
    def __unicode__(self): 
        return self.name 

我创建了模板,现在我有了商店名称和产品及其价格:

我如何计算这个价格?例如,在这张图片上,我选择的产品总数 = 17。我应该在 View 中创建一些东西,然后将其放入模板中,还是只将其写入模板中?

现在我有类似的东西:

{% for p in shop.product.all %} 
        {{p.cost}}  
{% endfor %} 

但接下来呢?它只显示这个值,但如何对此进行数学运算?我不知道。

我的看法:

def shop_detail(request, pk): 
    shop = get_object_or_404(Shop, pk=pk) 
    return render(request, 'shopbudget/shop_detail.html', {'shop': shop}) 

现在我应该创造什么?我创建了类似的东西:

def sum_of_count(request): 
    total = 0 
    for cost in shop.product.all: 
        total = total + cost 
        return total 

请您参考如下方法:

@willemoes 描述的方法可以正常工作,我唯一关心的是在 python 中而不是在数据库级别进行计算(性能提升)。 我建议您在数据库级别进行计算,在您的模型类(商店)中,您可以添加以下内容。

from django.db.models import Sum 
 
def calculate_cost(self, default=0.0): 
    cost = Product.objects.filter(shop__id=shop_pk).aggregate(total=Sum('cost')) 
    return cost['total'] or default 

该代码应该不昂贵,但如果开始需要一些时间返回,您可以使用“django 缓存”或“@cached_property”“缓存”该计算。 使用 django 的 cache framework .

def total_cost(self, default=0.0, expire=300): 
    key = "pcost_%s" % self.pk 
    cost = cache.get(key) 
    if cost:  # cache found! 
        return cost 
 
    cost = Product.objects.filter(shop__id=shop_pk).aggregate(total=Sum('cost')) 
    value = cost['total'] or default 
    cache.set(key, value, expire)  #after expire seconds will be deleted 
    return value 

使用 @cached_property

from django.utils.functional import cached_property 
 
@cached_property 
def total_cost(self): 
    cost = Product.objects.filter(shop__id=shop_pk).aggregate(total=Sum('cost')) 
    return cost['total'] or 0.0 

@cached_property 使用 memoization .它是一个普通的 python 属性。如果您想使“缓存”无效以强制重新计算,您必须执行以下操作:

# see the @cached_property docs for more info 
del your_model_instance.total_cost 

希望对你有帮助!