django:初始化对象时的RecursionError

时间:2016-08-23 19:11:41

标签: python django oop

所以我想为我的应用程序构建一个简单的购物车功能,只需添加,删除一件设备,并显示当前购物车列表。以下是此购物车的代码:(代码主要来自https://github.com/bmentges/django-cart

cart.py:

import datetime
from .models import Cart, Item, ItemManager

CART_ID = 'CART-ID'

class ItemAlreadyExists(Exception):
    pass

class ItemDoesNotExist(Exception):
    pass

class Cart:
    def __init__(self, request, *args, **kwargs):
        super(Cart, self).__init__()
        cart_id = request.session.get(CART_ID)
        if cart_id:
            try:
                cart = models.Cart.objects.get(id=cart_id, checked_out=False)
            except models.Cart.DoesNotExist:
                cart = self.new(request)
        else:
            cart = self.new(request)
        self.cart = cart

    def __iter__(self):
        for item in self.cart.item_set.all():
            yield item

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

    def add(self, equipment):
        try:
            item = models.Item.objects.get(
                cart=self.cart,
                equipment=equipment,
            )
        except models.Item.DoesNotExist:
            item = models.Item()
            item.cart = self.cart
            item.equipment = equipment
            item.save()
        else: #ItemAlreadyExists

            item.save()

    def remove(self, equipment):
        try:
            item = models.Item.objects.get(
                cart=self.cart,
                equipment=equipment,
            )
        except models.Item.DoesNotExist:
            raise ItemDoesNotExist
        else:
            item.delete()

    def count(self):
        result = 0
        for item in self.cart.item_set.all():
            result += 1 * item.quantity
        return result


    def clear(self):
        for item in self.cart.item_set.all():
            item.delete()

和models.py:

class Cart(models.Model):
    creation_date = models.DateTimeField(verbose_name=_('creation date'))
    checked_out = models.BooleanField(default=False, verbose_name=_('checked out'))

    class Meta:
        verbose_name = _('cart')
        verbose_name_plural = _('carts')
        ordering = ('-creation_date',)

    def __unicode__(self):
        return unicode(self.creation_date)

class ItemManager(models.Manager):
    def get(self, *args, **kwargs):
        if 'equipment' in kwargs:
            kwargs['content_type'] = ContentType.objects.get_for_model(type(kwargs['equipment']))
            kwargs['object_id'] = kwargs['equipment'].pk
            del(kwargs['equipment'])
        return super(ItemManager, self).get(*args, **kwargs)

class Item(models.Model):
    cart = models.ForeignKey(Cart, verbose_name=_('cart'))
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()

    objects = ItemManager()

    class Meta:
        verbose_name = _('item')
        verbose_name_plural = _('items')
        ordering = ('cart',)

    def __unicode__(self):
        return u'%d units of %s' % (self.quantity, self.equipment.__class__.__name__)

    # product
    def get_product(self):
        return self.content_type.get_object_for_this_type(pk=self.object_id)

    def set_product(self, equipment):
        self.content_type = ContentType.objects.get_for_model(type(equipment))
        self.object_id = equipment.pk

当试图显示当前购物车的视图时,我遇到了这个问题:

  

/ calbase / cart /的RecursionError   比较超出最大递归深度

基本上它会重复调用以下内容:

cart = Cart(request, creation_date=datetime.datetime.now()) 
cart = self.new(request) 
cart = Cart(request, creation_date=datetime.datetime.now()) 
cart = self.new(request) 

.....

我知道这是因为我在做cart = Cart(...)时正在调用 init ,这又回到了cart = self.new(请求)并尝试了几种方法解决这个问题,徒劳无功。有人能帮助我吗?

环境:

Request Method: GET
Request URL: http://127.0.0.1:8000/calbase/cart/

Django Version: 1.10
Python Version: 3.5.2
Installed Applications:
['calbase.apps.CalbaseConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'haystack',
 'whoosh']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

回溯:

File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py" in inner
  39.             response = get_response(request)

File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\views.py" in get_cart
  72.     return render_to_response('cart.html', dict(cart=Cart(request)))

File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\cart.py" in __init__
  22.             cart = self.new(request)

File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\cart.py" in __init__
  22.             cart = self.new(request)

File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\cart.py" in new
  30.         cart = Cart(request, creation_date=datetime.datetime.now())

Exception Type: RecursionError at /calbase/cart/
Exception Value: maximum recursion depth exceeded in comparison

1 个答案:

答案 0 :(得分:2)

您有两个名为Cart的单独类。重命名其中一个。