【发布时间】:2021-10-31 02:48:12
【问题描述】:
我使用会话来创建购物车。 我有一个产品模型和一个 Variant 模型,我在 Variant 模型中为我的产品着色和大小。这样我就可以拥有不同颜色和尺寸以及不同价格的产品。 我用 Session 创建的购物车有问题。 我遇到的问题是,如果产品有 3 种不同的颜色并且每种颜色都有不同的价格,我无法在购物车中显示价格,我不知道该怎么做。 我应该如何在模板中显示我的 Variant 模型的价格?
my Product model:
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.IntegerField(default=0)
my Variant model:
class Variants(models.Model):
name = models.CharField(max_length=100)
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_var',)
size = models.ForeignKey(Size, on_delete=models.CASCADE)
color = models.ForeignKey(Color, on_delete=models.CASCADE)
price = models.IntegerField(default=0)
my session cart :
CART_SESSION_ID = 'cart'
class Cart:
def __init__(self, request):
self.session = request.session
cart = self.session.get(CART_SESSION_ID)
if not cart:
cart = self.session[CART_SESSION_ID] = {}
self.cart = cart
def __iter__(self):
product_ids = self.cart.keys()
products = Product.objects.filter(id__in=product_ids)
cart = self.cart.copy()
for product in products:
cart[str(product.id)]['product'] = product
def add(self, product, quantity):
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0, 'price': str(product.total_price)}
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
self.session.modified = True
my view:
# show cart
def cart_details(request):
cart = Cart(request)
return render(request, 'cart/cart_details.html', {'cart': cart, })
# add to cart
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = CartAddForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product, quantity=cd['quantity'])
return redirect('cart:details')
my template for show product in cart:
{% for c in cart %}
<tr>
<td>{{ c.product.name }}</td>
<td>{{ c.product.price }}</td> # my problem!!!
</tr>
{% endfor %}
【问题讨论】:
标签: django django-models django-sessions