【问题标题】:How to develop Cart models and Cart Items model in django rest framework如何在django rest框架中开发Cart模型和Cart Items模型
【发布时间】:2021-05-17 03:14:35
【问题描述】:

我正在尝试在 django rest 框架中为后端创建模型。我看到的大多数开发人员使用两种模型,即 Cart 和 Cart Items 来创建购物车,如下所示:

class Cart(models.Model):

    owner = models.OneToOneField(User,
                                 related_name="cart",
                                 on_delete=models.CASCADE,
                                 null=True,
                                 blank=True)
    number_of_items = models.PositiveIntegerField(default=0)

    total = models.DecimalField(default=0.00,
                                max_digits=5,
                                decimal_places=2)

    created_at = models.DateTimeField(auto_now_add=True)

    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"User: {self.owner}, items in cart {self.number_of_items}"


class CartItem(models.Model):
    cart = models.ForeignKey(Cart,
                             on_delete=models.CASCADE)
    item = models.ForeignKey(Product,
                             on_delete=models.CASCADE)
    quantity = models.IntegerField()

我对为什么必须创建两个模型感到困惑。它的实际用途是什么?而且项目不应该是多对多字段而不是外键,因为我们应该在购物车上添加多个产品。

  1. 另外,为什么同时有 number_of_items 和数量?有什么区别??

我提出的模型:

类购物车(models.Model):

    owner = models.OneToOneField(User,related_name="cart",
                                 on_delete=models.CASCADE,
                                 null=True,
                                 blank=True)
    item = models.ManytoManyField(Product,blank =True, null =True)

    number_of_items = models.PositiveIntegerField(default=0)

    total = models.DecimalField(default=0.00,
                                max_digits=5,
                                decimal_places=2)

    created_at = models.DateTimeField(auto_now_add=True)

    updated_at = models.DateTimeField(auto_now=True)

【问题讨论】:

    标签: django django-models django-rest-framework model cart


    【解决方案1】:

    @Saroj Paudel - 这是我在电子商务项目中用于购物车模型的模型。我有一个推车模型。即引用了 product_id、user_id、数量(购物车中的商品数量)和添加日期的购物车。

    1 个产品可以属于 1 个或多个 caritem,1 个 caritem 可以有 1 个或多个产品。所以,本质上它是一个 M2M,但我选择 1 到 Many,因为除了我的 product_id 可能会为不同的用户重复许多项目之外,我没有看到任何伤害,但我可以接受这种重复。

    class CartItem(TimeStampedModel):
        date_added = models.DateTimeField(auto_now_add=True)
        quantity = models.IntegerField(default=1)
        product = models.ForeignKey(Product, unique=False, on_delete=models.PROTECT)
        user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
        ordered = models.BooleanField(default=False)
    

    【讨论】:

      猜你喜欢
      • 2013-05-19
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 2017-03-27
      • 2018-12-10
      • 2022-10-06
      • 1970-01-01
      • 2016-05-30
      相关资源
      最近更新 更多