【发布时间】: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()
我对为什么必须创建两个模型感到困惑。它的实际用途是什么?而且项目不应该是多对多字段而不是外键,因为我们应该在购物车上添加多个产品。
- 另外,为什么同时有 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