Django外键的模型字段未正确更新

时间:2014-06-23 14:37:18

标签: python django django-models foreign-key-relationship cart

所以我在尝试更新外键模型的字段时遇到了麻烦。我正在尝试通过另一个模型的方法更新该字段,但它似乎没有正常工作,因为我在运行tests.py时得到的值不正确。我正在尝试更新“total_purchased”的值。这是我实际上要完成的一个例子:

我正在使用Django 1.6.4

如果问题太长而无法总结,是否允许以下​​两行?我是在django类模型方法中做到的:

Ex: Model.ForeignKeyModel.field = some_value
    Model.ForeignKeyModel.save()

使用以下3种型号:

class Meal (models.Model):
    name = models.CharField(max_length=255)
    total_purchased = models.IntegerField(default=0, validators=[MaxValueValidator(capacity)])
    capacity = models.IntegerField(default=500)

class Item (models.Model):
    cart = models.ForeignKey(Cart)
    meal = models.ForeignKey(Meal)
    quantity = models.IntegerField(validators=[MinValueValidator(0)], default=0)

class Cart (models.Model):
    delivery = models.ForeignKey(DeliveryInfo)
    subscription = models.BooleanField(default=False)
    customer = models.ForeignKey(User)

    def add(self, meal, quantity):
        """ Dual Add/Remove from cart method, (quantity replaces current quantity) """
        item = Item.objects.get_or_create(cart=self, meal=meal)[0]
        remaining_capacity = item.meal.capacity - item.meal.total_purchased

        # Meal exists on our cart, so proceed with adding or removing
        if quantity <= remaining_capacity:

            if quantity == 0:
                # Add back whatever quantity the user didn't buy
                item.meal.total_purchased = 0
                item.meal.save()

                # Remove entire item from cart (quantity = 0)
                item.delete()

            elif quantity == item.quantity:
                # Do nothing if cart quantity equals current quantity
                pass

            else:
                if quantity < item.quantity:
                    # Decrement total purchased
                    item.meal.total_purchased -= (item.quantity - quantity)
                    item.meal.save()

                else:
                    # Increment total_purchased by the quantity we're adding to the cart
                    item.meal.total_purchased += (quantity - item.quantity)
                    item.meal.save()

            # Update the Cart
            item.quantity = quantity
            item.save()

            remaining_capacity = item.meal.capacity - item.meal.total_purchased

    else:
        exceeded = abs(remaining_capacity - quantity)
        raise ValidationError("Your cart exceeds the total remaining quantity by {0}!".format(exceeded))

更新后,它第一次工作,但似乎忽略了下一个添加到购物车方法调用,我最终在我的tests.py中得到以下内容: self.assertEqual(item.total_purchased,2) 断言错误:1!= 2

我不确定是不是因为购物车更新发生在tests.py中,或者我是以某种方式错误地保存数据。任何帮助将不胜感激,谢谢。

这里要求的是我的tests.py,我正在运行测试:

customer = User.objects.filter(pk=1)[0]
delivery_info = DeliveryInfo.objects.filter(owner=customer)[0]
cart_order = CartOrder.objects.create(owner=customer, delivery=delivery_info, subscription=False)

# Query the meal_items
curry_item = Meal.objects.get(pk=1)
burger_item = Meal.objects.get(pk=2)

# Add some meal items to our cart, the cart_order add method creates Items
cart_order.add(curry_item, 2)
cart_order.add(burger_item, 1)

self.assertEqual(burger_item.total_purchased, 1)

# Removing one item from the cart
cart_order.add(curry_item, 1)

# Doing nothing to the cart
cart_order.add(curry_item, 1)

**这是无法正确更新值的地方:**

# Adding an item to the cart
cart_order.add(burger_item, 2)
self.assertEqual(burger_item.total_purchased, 2)

1 个答案:

答案 0 :(得分:3)

这种情况正在发生,因为您使用的模型实例未更新 第一次拨打get_or_create时,它会创建Item并使用Meal中的meal=meal,而第二次获取Item并且不使用Meal meal的实例。

由于您已将item.meal的实例作为参数,因此可以将meal替换为burger_item,您应该会看到所需的结果。或者,您可以在添加后重新加载Meal或任何一餐。

你真的应该考虑使用F()表达式来增加,因为它们只在数据库端执行,并且可以帮助防止竞争条件。请注意,使用F()表达式会要求您重新加载# Update the Cart item.quantity = quantity item.save() 以查看其新值。

旁注,请注意

quantity == 0

Item的情况下被调用并删除Item,因为这会重新创建{{1}}。