首页 > django orm怎么根据表中的查询指定字段?

django orm怎么根据表中的查询指定字段?

product表如下:
class Product(models.Model):

name=models.CharField(u'名称',max_length=200,)
price=models.IntegerField(u'价格',)

我的product是一个productid列表,我通过这个列表来查询实际的product表的查询结果。
plist = request.POST.getlist('product')#这是post来的id列表。

查询如下:
prolist=Product.objects.filter(id__in=plist)

我现在想获得产品总价格,我的笨办法是先查到所有product,然后根据price的值,求和。

    if plist is not None : 
        totalprice=0
        prolist=Product.objects.filter(id__in=plist)
        price=[]
        for item in prolist:
            price.append(item.price)
            for p in price:                 
                totalprice+=p
                print totalprice

但实际上最后的totalprice并没有求和,只是第一个价格数字,查了好多网上的教程也没有找到办法,请问有更合适的办法吗?水平有限不得不求助各位,非常感谢!


第二个for循环少一层缩进就对了。另同楼上: 可用aggregation


Django是支持aggregation的,可以如下对price求和:

from django.db.models import Sum
ret = Product.objects.filter(id__in=plist).aggregate(Sum('price'))
【热门文章】
【热门文章】