【发布时间】:2019-07-07 21:46:47
【问题描述】:
我想计算产品的折扣。我正在使用 @property 在 models.py 中计算价格。但我面临的问题是产品表在产品应用程序(models.py)中,其中包含价格,但数量在购物车应用程序(models.py)中。总而言之,我想乘以 price*quantity。我面临的错误是 get_total_price 没有计算金额。 view.py
def cart_detail(request):
cart = Carts(request)
coupon_apply_form = CouponApplyForm()
context = {
'cart':cart,
'coupon_apply_form':coupon_apply_form
}
return render(request,'carts/coupon.html',context)
Cart/models.py
class CartItem(models.Model):
cart=models.ForeignKey('Cart',on_delete=models.SET_NULL,null=True,blank=True)
product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True)
quantity=models.IntegerField(default=1)
class Cart(models.Model):
product = models.ManyToManyField(Product, blank=True)
total= models.DecimalField( default=0.00, max_digits=100, decimal_places=2)
Product/models.py
class Product(models.Model):
price = models.DecimalField(decimal_places=2, max_digits=20, default=0.00)
在我的 Cart/models.py
class Carts(object):
"""docstring for Cart"""
def __init__(self, request):
"""initalize the cart"""
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
self.coupon_id = self.session.get('coupon_id')
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
@property
def coupon(self):
if self.coupon_id:
return Coupons.objects.get(id=self.coupon_id)
return None
def get_discount(self):
if self.coupon:
return (self.coupon.discount / Decimal('100')) * self.get_total_price()
return Decimal('0')
def get_total_price_after_discount(self):
return self.get_total_price() - self.get_discount()
在上面的代码中,当我从 get_total_price_after_discount 中删除 self.get_total_price 然后显示折扣价,否则显示 0.00。
购物车/template.html
<table>
{% if cart.coupon %}
<tr class="gray2">
{% block trans %}
{% with code=cart.coupon.code discount=cart.coupon.discount %}
<td colspan="2">"{{code}}" coupon ({{discount}})% off</td>
{% endwith %}
{% endblock trans %}
<td colspan="4"></td>
<td class="num neg"> {{cart.get_discount|floatformat:"2"}}</td>
</tr>
{% endif %}
<tr class="total">
<td>Total</td>
<td colspan="4"></td>
<td class="num">{{cart.get_total_price_after_discount|floatformat:"2"}}</td>
</tr>
</table>
但它显示的总数为 0.00。我也试过这样:
def get_total_price(self):
return self.product.price* self.cartitem.quantity
但是徒劳无功。请在这方面帮助我?
注意: 我在 cart/views.py 中创建了一个函数来计算总数。我可以在 cart/models.py 中调用使用该计算吗?
提前致谢
【问题讨论】:
标签: python django django-models django-forms django-views