【问题标题】:Check if string exists in Many-to-one relationships检查字符串是否存在于多对一关系中
【发布时间】:2018-09-26 16:22:06
【问题描述】:

我尝试在 Django 中编写一个简单的 Shopping-Cart 并具有以下模型:

class Product(models.Model):
    name = models.CharField(max_length=256)
    serial = models.CharField(max_length=128)
    def __str__(self):
        return self.name

class Cart(models.Model):
    user        = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    products    = models.ManyToManyField(Product, blank=True)
    updated     = models.DateTimeField(auto_now=True)
    timestamp   = models.DateTimeField(auto_now_add=True)

    objects = CartManager()

    def __str__(self):
        return str(self.id)


class CartEntry(models.Model):
    product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE)
    cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()

    def __str__(self):
        return str(self.id)

我将如何检查产品的 CartEntry 是否已经存在,所以当它已经存在时我可以增加数量 +1,或者当它不存在时创建一个 CartEntry?

我在想这样的事情:

def cart_update(request, id):

    product_id = id

    my_cart_id, my_cart = Cart.objects.get_or_create(user=request.user)

    product_obj = Product.objects.get(id=product_id)

    product_quantity = "1"

    for item in CartEntry.objects.filter(cart=my_cart_id):
        #check all products in CartEntry if it already exists
        if not item.product.exists():
            #Product does not exists yet - creating a CartEntry
            CartEntry.objects.create(cart=my_cart_id, product=product_obj, quantity=product_quantity)
        else:
            #Product does exists - incrementing the quantity

    return HttpResponseRedirect(reverse('list-products'))

【问题讨论】:

    标签: django django-views django-queryset


    【解决方案1】:

    我想我明白了:

    class CartEntry(models.Model):
        product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE)
        cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE)
        quantity = models.PositiveIntegerField()
    
        def __str__(self):
            return str(self.product.name)
    

    -

    from django.db.models import F
    
    def cart_update(request, id):
        product_id = id
    
        my_cart_id, my_cart_created = Cart.objects.get_or_create(user=request.user)
    
        product_obj = Product.objects.get(id=product_id)
    
        product_quantity = "1"
    
        items_in_cart = CartEntry.objects.filter(cart=my_cart_id)
    
        # if no products in cart, add product
        if not items_in_cart:
            CartEntry.objects.create(cart=my_cart_id, product=product_obj, quantity=product_quantity)
        else:
            # if product already exists in Cart, increment quantity +1
            if CartEntry.objects.filter(cart=my_cart_id).filter(product=product_obj):
                CartEntry.objects.filter(cart=my_cart_id, product=product_obj).update(quantity=F('quantity')+1)
            else:
                # product does not exist in Cart -> add it with quantity 1
                CartEntry.objects.create(cart=my_cart_id, product=product_obj, quantity=product_quantity)
    
    
        return HttpResponseRedirect(reverse('list-products'))
    

    当然欢迎编辑或其他(更好的)解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 2021-07-07
      • 2011-03-24
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2019-07-06
      相关资源
      最近更新 更多