我尝试加载页面时遇到此错误。 get() returned more than one Item -- it returned 2! Lookup parameters were {}
这是呈现页面的视图:
def get_category(request):
categories = Category.objects.all().prefetch_related('item')
# need to evaluate the HTTP method
if request.method == 'POST':
# add to order..create the bound form
postdata = request.POST.copy()
form = forms.PartialOrderItemForm(request.POST,postdata)
# check validation of posted data
if form.is_valid():
order.add_to_order(request)
# if test cookie worked, get rid of it
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
url =urlresolvers.reverse('order_index')
# redirect to order page
return HttpResponseRedirect(url)
else:
# it's a GET, create the unbound from. Note request as a Kwarg
form = forms.PartialOrderItemForm(request.GET)
# set the test cookie on our first GET request
request.session.set_test_cookie()
context={
'categories':categories,
'form':form,
# 'menu':menu,
}
return render_to_response('category.html',context,context_instance=RequestContext(request))
此视图在is_valid
,
def add_to_order(request):
postdata = request.POST.copy()
#get quantity added, return 0 if empty
quantity = postdata.get('quantity',0)
# fetch the item or return missing page error_message
i = get_object_or_404(Item,)
# get items in order
order_items = get_order_items(request)
item_in_orders = False
# check to see if item is already in order
for order_item in order_items:
if order_item.item.id == i.id:
#update the quantity if found
order_item.augment_quantity(quantity)
item_in_orders = True
if not item_in_orders:
# creat and save a new order item
oi = OrderItem()
oi.order_id = _order_id(request)
oi.quantity = quantity
oi.item = i
oi.save()
这里是Traceback
Traceback:
File "/home/mats-invasion/projects/f4l/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/mats-invasion/projects/f4l/f4l/live/views.py" in get_category
26. order.add_to_order(request)
File "/home/mats-invasion/projects/f4l/f4l/cart/order.py" in add_to_order
42. i = get_object_or_404(Item,)
File "/home/mats-invasion/projects/f4l/env/local/lib/python2.7/site-packages/django/shortcuts/__init__.py" in get_object_or_404
113. return queryset.get(*args, **kwargs)
File "/home/mats-invasion/projects/f4l/env/local/lib/python2.7/site-packages/django/db/models/query.py" in get
368. % (self.model._meta.object_name, num, kwargs))
Exception Type: MultipleObjectsReturned at /menu/
Exception Value: get() returned more than one Item -- it returned 2! Lookup parameters were {}
谢谢。
答案 0 :(得分:1)
在您的第i = get_object_or_404(Item,)
行尝试获取该项目,但您尚未为其指定任何过滤器查询,因此它将尝试Item.objects.get()
将返回所有对象(类似于{{1} })。当给定查询有多个对象时,.get()
and get_object_or_404()
会引发Item.objects.all()
异常。
所以你需要将你的行更新为:
MultipleObjectsReturned