from django.db import models
from django.core.exceptions import MultipleObjectsReturned


class OrderManager(models.Manager):
    def get_order_by_cart(self, request):
        # short circuit if they don't have a session yet.
        if not request.session.session_key:
            # manually set it as modified so it gets created for us
            request.session.modified = True
            return None
        cart_id = request.session.session_key
        lookup_kwargs = {"cart_id": cart_id}

        try:
            order, new = self.get_or_create(**lookup_kwargs)
            # associate the order with the cart.
            if new:
                order.cart_id = cart_id
                order.save()
        except MultipleObjectsReturned:
            order = self.filter(**lookup_kwargs).order_by("id")[0]
        return order
