Я хочу рассчитать скидку на товары. Я рассчитываю цену в models.py с помощью @property. Но проблема, с которой я сталкиваюсь, заключается в том, что таблица продуктов находится в приложении Product (models.py), в котором указана цена, а количество - в приложении Корзина (models.py). И для всего я хочу умножить цена * количество . Ошибка, с которой я сталкиваюсь, заключается в том, что 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)
Корзина / 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)
Продукт / models.py
class Product(models.Model):
price = models.DecimalField(decimal_places=2, max_digits=20, default=0.00)
В моей корзине / 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()
В приведенном выше коде, когда я удаляю self.get_total_price из get_total_price_after_discount, а затем отображается цена скидки, в противном случае она показывает 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.
Заранее спасибо