Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a model called OrderItem

class OrderItem(models.Model):
    customer = models.ForeignKey(
        User, on_delete=models.SET_NULL, blank=True, null=True)
    product = models.ForeignKey(
        Product, on_delete=models.SET_NULL, blank=True, null=True)
    order = models.ForeignKey(
        Order, on_delete=models.SET_NULL, blank=True, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

and a model called Order

class Order(models.Model):
    customer = models.ForeignKey(
        User, on_delete=models.SET_NULL, blank=True, null=True)
    date_ordered = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False, null=True, blank=False)
    transaction_id = models.CharField(max_length=200, null=True)

Now in my views.py I have an OrderItem model order instance. And in my Order model I need to set its order instance to complete. I'm trying something as follows:

orderID = OrderItem.objects.filter(order_id=4)
#lets say there are more than one order_id with the value of 4
for order in orderID:
    order = Order.objects.get(id=orderID)
    order.complete=True
    order.save()

this code gives me:

ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.

How to fix this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
257 views
Welcome To Ask or Share your Answers For Others

1 Answer

orderID in your example can be list, possibly of size greater than one. This makes the following to fail:

orderID=OrderItem.objects.filter(order_id=4)
#lets say there are more than one order_id with the value of 4
for order in orderID:
       order = Order.objects.get(id=orderID)  # FAIL: list passed as ID
       order.complete=True
       order.save()

You should pass order as an argument to .get() function or use related model, like

order_items=OrderItem.objects.filter(order_id=4)
for order_item in order_items:
       order = order_item.order
       order.complete=True
       order.save()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...