0

我很难修复 valueError, '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.

谢谢你。

4

1 回答 1

1

更新您的视图代码以添加新项目

if not item_in_orders:
    # creat and save a new order item
    oi = OrderItem()
    oi.quantity = quantity
    oi.order_id = _order_id(request)
    oi.save()
    #save oi first, then add i to item
    oi.item.add(i)
于 2013-01-11T09:13:21.993 回答