I
I
Ilya Oskin2017-01-05 12:22:01
Django
Ilya Oskin, 2017-01-05 12:22:01

How to serialize such an object in Django?

Good afternoon! You need to serialize an object like this:

class Cart(object):
    def __init__(self, request):
        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

    def add(self, product, quantity=1, update_quantity=False):
        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):
        self.session[settings.CART_SESSION_ID] = self.cart
        self.session.modified = True

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

    def __iter__(self):
        product_ids = self.cart.keys()
        products = Product.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):
        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

Not strong in Django Rest framework - I can only serialize simple models through generic serializers, but there are problems with a more non-trivial object

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eIGato, 2017-01-14
@eIGato

lots of options.
1. the easiest, but not the best: write your bike. add methods like __dumps__() and __loads__(), the first of which turns the object into a string (in fact, you only need session and cart there), and the second one initializes the object from a string.
2. much better: instead of one serializer, take another. there are a lot of them in python, starting with the standard Pickle, and ending with other common formats: JSON, PHPSerialize, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question