我很難修復一個值錯誤, 'OrderItem' instance needs to have a primary key value before a many-to-many relationship can be used.
我知道我必須做些什麼.add()
,但我不知道如何。 這裏是OrderItem model
處理一個值錯誤
class OrderItem(SmartModel):
order_id = models.CharField(max_length=50,db_index=True)
date_added = models.DateTimeField(auto_now_add=True)
quantity = models.IntegerField(default=0)
item = models.ManyToManyField(Item)
class Meta:
db_table='order_items'
def __unicode__(self):
return "%s" % (self.order_id)
這裏是我的意見做,
def add_to_order(request):
postdata = request.POST.copy()
#get item slug from post data, return blank if empty
# item_slug = postdata.get('item_slug','')
#get quantity added, return 1 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.item = i
oi.quantity = quantity
oi.order_id = _order_id(request)
oi.save()
,這裏是回溯:
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
25. order.add_to_order(request)
File "/home/mats-invasion/projects/f4l/f4l/cart/order.py" in add_to_order
48. oi.item = i
File "/home/mats-invasion/projects/f4l/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in __set__
832. manager = self.__get__(instance)
File "/home/mats-invasion/projects/f4l/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in __get__
819. through=self.field.rel.through,
File "/home/mats-invasion/projects/f4l/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in __init__
536. raise ValueError("%r instance needs to have a primary key value before a many-to-many relationship can be used." % instance.__class__.__name__)
Exception Type: ValueError at /menu/
Exception Value: 'OrderItem' instance needs to have a primary key value before a many-to-many relationship can be used.
謝謝。
嘗試把'oi.item = i'最後,後'oi.save' – DanielB
didnt work..thanks壽 –