def encode(self, formatter=None):
        """Return a representation of the cart as a JSON-response.

        Parameters
        ----------
        formatter : func, optional
            A function that accepts the cart representation and returns
            its formatted version.

        Returns
        -------
        django.http.JsonResponse

        Examples
        --------
        Assume that items with primary keys "1" and "4" are already in
        the cart.

        >>> cart = Cart(request)
        >>> def format_total_price(cart_repr):
        ...     return intcomma(cart_repr['totalPrice'])
        ...
        >>> json_response = cart.encode(format_total_price)
        >>> json_response.content
        b'{
            "items": {
                '1': {"price": 100, "quantity": 10, "total": 1000},
                '4': {"price": 50, "quantity": 20, "total": 1000},
            },
            "itemCount": 2,
            "totalPrice": "2,000",
        }'

        """
        items = {}
        # The prices are converted to strings, because they may have a
        # type that can't be serialized to JSON (e.g. Decimal).
        for item in self.items.values():
            pk = str(item.obj.pk)
            items[pk] = {
                'price': str(item.price),
                'quantity': item.quantity,
                'total': item.total,
            }
        cart_repr = {
            'items': items,
            'itemCount': self.item_count,
            'totalPrice': str(self.total_price),
        }
        if formatter:
            cart_repr = formatter(cart_repr)
        return JsonResponse(cart_repr)
def encode ( self , formatter = None ) : items = { } for item in self . items . values ( ) : pk = str ( item . obj . pk ) items [ pk ] = { 'price' : str ( item . price ) , 'quantity' : item . quantity , 'total' : item . total , } cart_repr = { 'items' : items , 'itemCount' : self . item_count , 'totalPrice' : str ( self . total_price ) , } if formatter : cart_repr = formatter ( cart_repr ) return JsonResponse ( cart_repr )
Return a representation of the cart as a JSON-response.

        Parameters
        ----------
        formatter : func, optional
            A function that accepts the cart representation and returns
            its formatted version.

        Returns
        -------
        django.http.JsonResponse

        Examples
        --------
        Assume that items with primary keys "1" and "4" are already in
        the cart.

        >>> cart = Cart(request)
        >>> def format_total_price(cart_repr):
        ...     return intcomma(cart_repr['totalPrice'])
        ...
        >>> json_response = cart.encode(format_total_price)
        >>> json_response.content
        b'{
            "items": {
                '1': {"price": 100, "quantity": 10, "total": 1000},
                '4': {"price": 50, "quantity": 20, "total": 1000},
            },
            "itemCount": 2,
            "totalPrice": "2,000",
        }'