Как добавить в корзину варианты товара

Я пытаюсь создать варианты товара со значениями: цвет, размер. Как вы видите, данные корзины хранятся в сессии. Трудность для меня заключается в том что я не могу понять как должно происходить добавление товаров или их вариантов в корзину, и каким образом обновить колличество если товар 1 с цветом красный уже в корзине и я добавляю товар 1 с таким же цветом. Так же вопрос как исключить обновление колличества если товар 1 но цвет черный.

#cart/cart.py

class Cart(object):
def __init__(self, request):
    # initialize the cart
    self.session = request.session
    cart = self.session.get(settings.CART_SESSION_ID)
    if not cart:
        # save empty cart in the session
        cart = self.session[settings.CART_SESSION_ID] = {}
    self.cart = cart
    # store current applied coupon
    self.coupon_id = self.session.get('coupon_id')

def add(self, product, quantity=1, update_quantity=False):
    # add product or update their quantity
    product_id = str(product.id)
    if product_id not in self.cart:
        self.cart[product_id] = {
            'quantity': 0, 'price': str(product.price)}
    if update_quantity:
        self.cart[product_id]['quantity'] = quantity
    else:
        self.cart[product_id]['quantity'] += quantity
    self.save()

def save(self):
    # mark session as modified to be shore thats saved
    self.session.modified = True

def remove(self, product):
    # remove product from the cart
    product_id = str(product.id)
    if product_id in self.cart:
        del self.cart[product_id]
        self.save()

def __iter__(self):
    # iterate over the items in the cart
    # and get the products from the database
    product_ids = self.cart.keys()
    # get the product object and add them to the cart
    products = Product.objects.filter(id__in=product_ids)

    cart = self.cart.copy()
    for product in products:
        cart[str(product.id)]['product'] = product

    for item in cart.values():
        item['price'] = Decimal(item['price'])
        item['total_price'] = item['price'] * item['quantity']
        yield item

def __len__(self):
    # count all items in the cart
    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):
    # remove cart from session
    del self.session[settings.CART_SESSION_ID]
    self.save()

@property
def coupon(self):
    if self.coupon_id:
        return Coupon.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()

# product/models.py

class Product(models.Model):
    name = models.CharField(max_length=200,
                            db_index=True)
    slug = models.SlugField(max_length=200,
                            db_index=True)
    description = models.TextField()
    category = models.ForeignKey(Category,
                                 related_name='products',
                                 on_delete=models.CASCADE)
    image = models.ImageField(upload_to="images")
    price = models.DecimalField(max_digits=10,
                                decimal_places=2)
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name',)
        index_together = (('id', 'slug'),)

    def __str__(self):
        return self.name

# cart/views.py

@require_POST
def cart_add(request, product_id):
  cart = Cart(request)
  product = get_object_or_404(Product, id=product_id)
  form = CartAddProductForm(request.POST)
  if form.is_valid():
    cd = form.cleaned_data
    cart.add(product=product,
             quantity=cd['quantity'],
             update_quantity=cd['update'])
  return redirect('cart:cart_detail')


def cart_remove(request, product_id):
  cart = Cart(request)
  product = get_object_or_404(Product, id=product_id)
  cart.remove(product)
  return redirect('cart:cart_detail')


def cart_detail(request):
  cart = Cart(request)
  if cart.__len__() > 0:
    for item in cart:
      item['update_quantity_form'] = CartAddProductForm(
          initial={'quantity': item['quantity'],
                   'update': True})
    coupon_apply_form = CouponApplyForm()
    return render(request,
                  'cart/cart_detail.html',
                  {'cart': cart,
                   'coupon_apply_form': coupon_apply_form})
  else:
    messages.success(
        request, "Ваша корзина пуста. Добавьте товары для просмотра содержимого корзины.")
    return redirect("shop:product_list")

Ответы (0 шт):