使用一个表单

时间:2017-07-01 17:09:58

标签: python django

我正在建造一个购物车。我有Product模型和ShoppingCartItem模型:

class Product(models.Model):
    name = models.CharField(max_length=64)
    description = models.TextField(blank=True)
    unit = models.CharField(max_length=16)
    price_per_unit = models.DecimalField(max_digits=11, decimal_places=2)
    image = StdImageField(default="default.jpg", variations={
        'thumbnail': {"width": 100, "height": 100, "crop": True}
    })

    def __str__(self):
        return self.name


class ShoppingCartItem(models.Model):
    user = models.ForeignKey(django_settings.AUTH_USER_MODEL, related_name='cart_items', on_delete=models.CASCADE)
    product  = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=1)

    # Update the quantity of an item in the shopping cart
    def update_quantity(self, quantity):
        if quantity <= 0:
            # If user sets quantity to 0 or less, delete the item.
            self.remove_item()
        else:
            self.quantity = quantity
            self.save()

    # Remove item from the shopping cart
    def remove_item(self):
        self.delete()

    def get_ext_total(self):
        return Decimal(self.product.price_per_unit * self.quantity)

我希望UX能够通过文本框一次更新数量ShoppingCartItem。我查看了表单集和内联表单集,但它们似乎更适合于在每个对象中创建对象和ManyToMany关系,而不是一次更新多个对象。以下是我的购物车示例:

Shopping Cart List

最好的方法是做什么?

1 个答案:

答案 0 :(得分:0)

我知道为更新数据库进行多次查询并且您希望在一次调用中更新多个对象属性不是一个好主意。但是,如果属性值不同,则在ORM中没有简单的方法。

您可以实施以下其中一项:

单次更新

通常,在数据库中使用primary进行单次更新非常快,如果更新次数不是很高,这就足够了。

def update_cart(user_id, cart):
   for product_id, quantity in cart.items():
       ShoppingCartItem.objects.get(user__id=user_id, product__id=product_id).update(quantity=quantity)

使用事务

进行单次更新
from django.db import transaction
    def update_cart(user_id, cart):
        with transaction.atomic():
            for product_id, quantity in cart.items():
                ShoppingCartItem.objects.get(user__id=user_id, product__id=product_id).update(quantity=quantity)

使用transaction.atomic所有更新都将分组到一个事务中。如果我们有大量的更新,这将优化数据库交互。