【问题标题】:How to calculate total price of a product in models in Django?如何在 Django 中计算模型中产品的总价格?
【发布时间】: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


    【解决方案1】:

    我们可以在Cart 模型中计算聚合,例如:

    from decimal import Decimal
    from django.db.models import F, Sum
    
    class Cart(models.Model):
    
        # ...
    
        @property
        def total_price(self):
            return self.cartitem_set.aggregate(
                total_price=Sum(F('quantity') * F('product__price'))
            )['total_price'] or Decimal('0')

    对于Cart,我们可以将其渲染为:

    &lt;td class="num"&gt;{{ <b>cart.total_price</b>|floatformat:"2" }}&lt;/td&gt;

    【讨论】:

    • 非常感谢您的回复。但它没有打印任何东西@Willem Sir 甚至没有 0
    • @Samavi: 模板中的cartCart 对象吗?
    • @Samavi:你能分享一下你正在使用的视图吗?您确实将模板更改为{{ cart.total_price|...}} 对吗?
    • 是的,我也分享过。 @Willem 我编辑了我的问题 cart/models.py 请查看以进一步了解
    • @Samavi:但问题不包含此处触发的视图功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2021-09-07
    • 2021-07-19
    • 2020-11-12
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多