模型中对象的总和

时间:2013-10-28 23:26:23

标签: python django django-models model

我正在尝试使用名为django-cart的Django电子商务插件进行编码。我想找到购物车中所有商品的价格总和。购物车型号具有以下代码:

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Cart(models.Model):
    creation_date = models.DateTimeField(verbose_name=_('creation date'))
    checked_out = models.BooleanField(default=False, verbose_name=_('checked out'))
    def _valor_carrinho(self):
        return self.objects.all().aggregate(Sum('total_price'))
    valor_carrinho = property(_valor_carrinho)

    class Meta:
        verbose_name = _('cart')
        verbose_name_plural = _('carts')
        ordering = ('-creation_date',)

    def __unicode__(self):
        return unicode(self.creation_date)    

class ItemManager(models.Manager):
    def get(self, *args, **kwargs):
        if 'product' in kwargs:
            kwargs['content_type'] = ContentType.objects.get_for_model(type(kwargs['product']))
            kwargs['object_id'] = kwargs['product'].pk
            del(kwargs['product'])
        return super(ItemManager, self).get(*args, **kwargs)

class Item(models.Model):
    cart = models.ForeignKey(Cart, verbose_name=_('cart'))
    quantity = models.PositiveIntegerField(verbose_name=_('quantity'))
    unit_price = models.DecimalField(max_digits=18, decimal_places=2, verbose_name=_('unit price'))
    # product as generic relation
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    link_item = models.CharField(max_length=100)
    tipo_item = models.CharField(max_length=50)
    cor_item = models.CharField(max_length=50, blank=True)
    modelo_item = models.CharField(max_length=50, blank=True)
    tamanho_item = models.CharField(max_length=50, blank=True)

    objects = ItemManager()

    class Meta:
        verbose_name = _('item')
        verbose_name_plural = _('items')
        ordering = ('cart',)

    def __unicode__(self):
        return u'%d units of %s' % (self.quantity, self.product.__class__.__name__)

    def total_price(self):
        return self.quantity * self.unit_price
    total_price = property(total_price)

    # product
    def get_product(self):
        return self.content_type.get_object_for_this_type(id=self.object_id)

    def set_product(self, product):
        self.content_type = ContentType.objects.get_for_model(type(product))
        self.object_id = product.pk

    product = property(get_product, set_product)

我正在尝试使用valor_carrinho(对于代码中的葡萄牙语和英语之间的混淆),作为购物车中所有项目的total_price字段的总和。但是当我在模板中使用它时,它什么都不返回。我做错了什么?

3 个答案:

答案 0 :(得分:1)

我认为应该是:

def _valor_carrinho(self):
    return self.item_set.all().aggregate(Sum('total_price'))

要获取特定Cart个实例的所有项目,我不确定total_price是否适用于此处,但要访问购物车的商品item_set,希望这足以让开始吧!

正在使用的概念是反向外键查找,解释为here

答案 1 :(得分:0)

我不确定这是否有效,因为我认为聚合进入数据库层并且total_price已被定义为属性。我要进行非规范化,并将total_price的等价物作为一个字段,以便我可以使用聚合函数。

答案 2 :(得分:0)

尝试以下代码,它适用于我,因此它可能适合您:

view.py

def get_cart(request):
    cart = Cart(request)
    cart.summary()
    return render_to_response('cart.html', dict(cart=Cart(request)),{'cart':cart})

cart.html

<h3> Total : {{ cart.summary }}</h3>