Py学习  »  Django

Django为购物车和产品添加其他型号的列表

Omar Alhussani • 4 年前 • 2101 次点击  

我正在尝试创建一个商店,用户可以添加销售中的产品,其他用户可以将其添加到购物车中 我不知道如何让购物车包含多种产品及其数量。

class Product(models.Model):
    name = models.TextField()
    description = models.TextField()
    price = models.FloatField()
    quantity = models.FloatField()
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class Cart(models.Model):
    #list of products
    #list of quantities
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128151
文章 [ 1 ]  |  最新文章 4 年前
Willem Van Onsem
Reply   •   1 楼
Willem Van Onsem    5 年前

你可以在两者之间建立一个模型,并将其用作 through=… [Django-doc] 模型在这个模型中,我们使用 ForeignKey 到 Product A. 外国钥匙 到 Cart ,以及 IntegerField 数量:

class Product(models.Model):
    name = models.TextField()
    description = models.TextField()
    price = models.FloatField()
    quantity = models.FloatField()
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class Cart(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    products = models.ManyToManyField(
        Product,
        related_name='carts',
        through='CartProduct'
    )

class CartProduct(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

    class Meta:
        constraints = [
            models.UniqueField(fields=['product', 'cart'], name='unique_product_cart')
        ]

因此,您可以通过创建(或更新) CartOrder 在给定的情况下 product 和 cart .如果购物车和产品的组合已经存在,您可以增加其数量。

您还可以在 mycart.cardproduct_set.all() queryset要获取数量,我们可以打印产品名称及其数量,例如:

mycart = …  # some cart
for cartproduct in mycart.cartproduct_set.select_related('product'):
    print(f'{cartproduct.product.name}: {cartproduct.quantity}')