refactor the cart logic to adjust with the models either

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite












Adding the items to the cart is very crucial. I have a session based shopping cart and I need to adjust that shopping cart along with the model because I will need the cart data or cart items in the database either.



Here is the models for the cart



class Cart(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
items = models.ManyToManyField(Variation, through='CartItem')
quantity = models.PositiveIntegerField(default=1)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)
tax_percentage = models.DecimalField(max_digits=10, decimal_places=5, default=0.085)
tax_total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)
total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)


class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
item = models.ForeignKey(Variation, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
line_item_total = models.DecimalField(max_digits=10, decimal_places=2)


carts.py



CART_ID = 'cart-id'


class Cart(Object):

def __init__(self, request):
"""
Initialize the cart
"""
self.session = request.session
# get the current session from request.session.get(CART_ID)
cart = self.session.get(CART_ID)
if not cart: # cart is not present in the session
# save an empty cart in the session
# but we expect our cart dictionary to use product ids as keys
# and a dictionary with quantity and price as value for each key
# by that we can gurantee same product is not added twice
cart = self.session[CART_ID] =
else:
try:
cart = models.Cart.objects.get(id=cart)
except models.Cart.DoesNotExist:
cart = self.session[CART_ID] =
self.cart = cart


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 objects and add them to the cart
products = models.Variation.objects.filter(id__in=product_ids)
for product in products:
self.cart[str(product.id)]['product'] = product
for item in self.cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item


def __len__(self):
"""
Count all the 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):
# empty cart
self.session[CART_ID] =
self.session.modified = True


def new(self, request):
cart = models.Cart(timestamp=datetime.datetime.now())
cart.save()
request.session[CART_ID] = cart.id
return cart


def add(self, product, quantity=1, update_quantity=False):
"""
Add a product to the cart or update its quantity for True
or the new quantity needs to be added to the existing quantity
if it is False. We use the product id as a key and convert it to string
because django uses JSON to serialize session data.
"""
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):
# update the session cart
self.session[CART_ID] = self.cart
# mark the session as modified to make sure it is saved
self.session.modified = True


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


with the models i have, how do i refactor the above code to adjust with the models i have now so i will have track of the cart in the databases?







share|improve this question

























    up vote
    0
    down vote

    favorite












    Adding the items to the cart is very crucial. I have a session based shopping cart and I need to adjust that shopping cart along with the model because I will need the cart data or cart items in the database either.



    Here is the models for the cart



    class Cart(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
    items = models.ManyToManyField(Variation, through='CartItem')
    quantity = models.PositiveIntegerField(default=1)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)
    tax_percentage = models.DecimalField(max_digits=10, decimal_places=5, default=0.085)
    tax_total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)
    total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)


    class CartItem(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    item = models.ForeignKey(Variation, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=1)
    line_item_total = models.DecimalField(max_digits=10, decimal_places=2)


    carts.py



    CART_ID = 'cart-id'


    class Cart(Object):

    def __init__(self, request):
    """
    Initialize the cart
    """
    self.session = request.session
    # get the current session from request.session.get(CART_ID)
    cart = self.session.get(CART_ID)
    if not cart: # cart is not present in the session
    # save an empty cart in the session
    # but we expect our cart dictionary to use product ids as keys
    # and a dictionary with quantity and price as value for each key
    # by that we can gurantee same product is not added twice
    cart = self.session[CART_ID] =
    else:
    try:
    cart = models.Cart.objects.get(id=cart)
    except models.Cart.DoesNotExist:
    cart = self.session[CART_ID] =
    self.cart = cart


    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 objects and add them to the cart
    products = models.Variation.objects.filter(id__in=product_ids)
    for product in products:
    self.cart[str(product.id)]['product'] = product
    for item in self.cart.values():
    item['price'] = Decimal(item['price'])
    item['total_price'] = item['price'] * item['quantity']
    yield item


    def __len__(self):
    """
    Count all the 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):
    # empty cart
    self.session[CART_ID] =
    self.session.modified = True


    def new(self, request):
    cart = models.Cart(timestamp=datetime.datetime.now())
    cart.save()
    request.session[CART_ID] = cart.id
    return cart


    def add(self, product, quantity=1, update_quantity=False):
    """
    Add a product to the cart or update its quantity for True
    or the new quantity needs to be added to the existing quantity
    if it is False. We use the product id as a key and convert it to string
    because django uses JSON to serialize session data.
    """
    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):
    # update the session cart
    self.session[CART_ID] = self.cart
    # mark the session as modified to make sure it is saved
    self.session.modified = True


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


    with the models i have, how do i refactor the above code to adjust with the models i have now so i will have track of the cart in the databases?







    share|improve this question





















      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      Adding the items to the cart is very crucial. I have a session based shopping cart and I need to adjust that shopping cart along with the model because I will need the cart data or cart items in the database either.



      Here is the models for the cart



      class Cart(models.Model):
      user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
      items = models.ManyToManyField(Variation, through='CartItem')
      quantity = models.PositiveIntegerField(default=1)
      timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
      updated = models.DateTimeField(auto_now_add=False, auto_now=True)
      subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)
      tax_percentage = models.DecimalField(max_digits=10, decimal_places=5, default=0.085)
      tax_total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)
      total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)


      class CartItem(models.Model):
      cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
      item = models.ForeignKey(Variation, on_delete=models.CASCADE)
      quantity = models.PositiveIntegerField(default=1)
      line_item_total = models.DecimalField(max_digits=10, decimal_places=2)


      carts.py



      CART_ID = 'cart-id'


      class Cart(Object):

      def __init__(self, request):
      """
      Initialize the cart
      """
      self.session = request.session
      # get the current session from request.session.get(CART_ID)
      cart = self.session.get(CART_ID)
      if not cart: # cart is not present in the session
      # save an empty cart in the session
      # but we expect our cart dictionary to use product ids as keys
      # and a dictionary with quantity and price as value for each key
      # by that we can gurantee same product is not added twice
      cart = self.session[CART_ID] =
      else:
      try:
      cart = models.Cart.objects.get(id=cart)
      except models.Cart.DoesNotExist:
      cart = self.session[CART_ID] =
      self.cart = cart


      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 objects and add them to the cart
      products = models.Variation.objects.filter(id__in=product_ids)
      for product in products:
      self.cart[str(product.id)]['product'] = product
      for item in self.cart.values():
      item['price'] = Decimal(item['price'])
      item['total_price'] = item['price'] * item['quantity']
      yield item


      def __len__(self):
      """
      Count all the 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):
      # empty cart
      self.session[CART_ID] =
      self.session.modified = True


      def new(self, request):
      cart = models.Cart(timestamp=datetime.datetime.now())
      cart.save()
      request.session[CART_ID] = cart.id
      return cart


      def add(self, product, quantity=1, update_quantity=False):
      """
      Add a product to the cart or update its quantity for True
      or the new quantity needs to be added to the existing quantity
      if it is False. We use the product id as a key and convert it to string
      because django uses JSON to serialize session data.
      """
      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):
      # update the session cart
      self.session[CART_ID] = self.cart
      # mark the session as modified to make sure it is saved
      self.session.modified = True


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


      with the models i have, how do i refactor the above code to adjust with the models i have now so i will have track of the cart in the databases?







      share|improve this question











      Adding the items to the cart is very crucial. I have a session based shopping cart and I need to adjust that shopping cart along with the model because I will need the cart data or cart items in the database either.



      Here is the models for the cart



      class Cart(models.Model):
      user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
      items = models.ManyToManyField(Variation, through='CartItem')
      quantity = models.PositiveIntegerField(default=1)
      timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
      updated = models.DateTimeField(auto_now_add=False, auto_now=True)
      subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)
      tax_percentage = models.DecimalField(max_digits=10, decimal_places=5, default=0.085)
      tax_total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)
      total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)


      class CartItem(models.Model):
      cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
      item = models.ForeignKey(Variation, on_delete=models.CASCADE)
      quantity = models.PositiveIntegerField(default=1)
      line_item_total = models.DecimalField(max_digits=10, decimal_places=2)


      carts.py



      CART_ID = 'cart-id'


      class Cart(Object):

      def __init__(self, request):
      """
      Initialize the cart
      """
      self.session = request.session
      # get the current session from request.session.get(CART_ID)
      cart = self.session.get(CART_ID)
      if not cart: # cart is not present in the session
      # save an empty cart in the session
      # but we expect our cart dictionary to use product ids as keys
      # and a dictionary with quantity and price as value for each key
      # by that we can gurantee same product is not added twice
      cart = self.session[CART_ID] =
      else:
      try:
      cart = models.Cart.objects.get(id=cart)
      except models.Cart.DoesNotExist:
      cart = self.session[CART_ID] =
      self.cart = cart


      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 objects and add them to the cart
      products = models.Variation.objects.filter(id__in=product_ids)
      for product in products:
      self.cart[str(product.id)]['product'] = product
      for item in self.cart.values():
      item['price'] = Decimal(item['price'])
      item['total_price'] = item['price'] * item['quantity']
      yield item


      def __len__(self):
      """
      Count all the 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):
      # empty cart
      self.session[CART_ID] =
      self.session.modified = True


      def new(self, request):
      cart = models.Cart(timestamp=datetime.datetime.now())
      cart.save()
      request.session[CART_ID] = cart.id
      return cart


      def add(self, product, quantity=1, update_quantity=False):
      """
      Add a product to the cart or update its quantity for True
      or the new quantity needs to be added to the existing quantity
      if it is False. We use the product id as a key and convert it to string
      because django uses JSON to serialize session data.
      """
      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):
      # update the session cart
      self.session[CART_ID] = self.cart
      # mark the session as modified to make sure it is saved
      self.session.modified = True


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


      with the models i have, how do i refactor the above code to adjust with the models i have now so i will have track of the cart in the databases?









      share|improve this question










      share|improve this question




      share|improve this question









      asked Jun 24 at 7:25









      Serenity

      1464




      1464

























          active

          oldest

          votes











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f197155%2frefactor-the-cart-logic-to-adjust-with-the-models-either%23new-answer', 'question_page');

          );

          Post as a guest



































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes










           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f197155%2frefactor-the-cart-logic-to-adjust-with-the-models-either%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Greedy Best First Search implementation in Rust

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          C++11 CLH Lock Implementation