我正在尝试使用名为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
购物车中所有项目的字段总和。但是当我在模板中使用它时,它什么也不返回。我究竟做错了什么?