如何在一个购物车中添加多个模型(Django)
Posted
技术标签:
【中文标题】如何在一个购物车中添加多个模型(Django)【英文标题】:How to add multiple number of models in one cart (Django) 【发布时间】:2021-08-16 12:23:51 【问题描述】:我使用 PostgresSQL 作为 DB,Django 作为 后端 和 HTML、CSS、 Javascript 作为前端。我有多个产品Models
,我想将所有这些模型添加到一个购物车中。所以,我已经成功地在购物车中添加了 一个 模型。但是
我想添加不同的产品,例如冰箱、风扇、洗衣机 机器,...等在一个购物车中
那么,它将如何工作?
代码在这里:
models.py
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
full_name = models.CharField(max_length=200)
joined_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.full_name
class Regrigeratior(models.Model):
image_src = models.URLField(max_length=300,null=True, blank=True)
name = models.CharField(max_length=200, db_index=True, verbose_name="processor name")
brand = models.CharField(max_length = 300, null=True, blank=True)
....
def __str__(self):
return self.name
class Fans(models.Model):
image_src = models.URLField(max_length=300,null=True, blank=True)
name = models.CharField(max_length=200, db_index=True, verbose_name="processor name")
brand = models.CharField(max_length = 300, null=True, blank=True)
....
def __str__(self):
return self.name
.
.
.
class Cart(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
total = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "Cart: " + str(self.id)
#
class CartProduct(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
refrigerator = models.ForeignKey(Refrigerator, on_delete=models.CASCADE)
rate = models.PositiveIntegerField()
quantity = models.PositiveIntegerField()
subtotal = models.PositiveIntegerField()
def __str__(self):
return "Cart: " + str(self.cart.id) + " CartProduct: " + str(self.id)
我已成功将冰箱模型添加到购物车中
views.py
class AddToCartView(TemplateView):
template_name = "status.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
refrigerator_id = self.kwargs['ref_id']
refrigerator_obj = Refrigerator.objects.get(id = refrigerator_id)
cart_id = self.request.session.get("cart_id", None)
if cart_id:
cart_obj = Cart.objects.get(id = cart_id)
this_product_in_cart = cart_obj.cartproduct_set.filter(refrigerator = refrigerator_obj)
if this_product_in_cart.exists():
cartproduct = this_product_in_cart.last()
cartproduct.quantity += 1
cartproduct.subtotal += refrigerator_obj.price
cartproduct.save()
cart_obj.total += refrigerator_obj.price
cart_obj.save()
else:
cartproduct = CartProduct.objects.create(
cart = cart_obj, refrigerator = refrigerator_obj, rate = refrigerator_obj.price, quantity = 1, subtotal = refrigerator_obj.price)
cart_obj.total += processor_obj.price
cart_obj.save()
else:
cart_obj = Cart.objects.create(total=0)
self.request.session['cart_id'] = cart_obj.id
cartproduct = CartProduct.objects.create(
cart = cart_obj, refrigerator = refrigerator_obj, rate = refrigerator_obj.price, quantity = 1, subtotal = refrigerator_obj.price)
cart_obj.total += refrigerator_obj.price
cart_obj.save()
return context
所以,现在我将 Fan 作为模特(以及更多模特)。那么它将如何添加到同一个购物车中呢?
【问题讨论】:
您好,您正在建立一个电子商务网站吗? 是的,我正在建立一个电子商务网站 好吧,那你写的逻辑效率不高,也不好。 您需要使用通用关系,以便 django 使用内容类型 ID 和对象 ID 链接到任何类型的对象。文档在这里; docs.djangoproject.com/en/3.2/ref/contrib/contenttypes/… @santoshChauhan 看看这里; djangopackages.org/grids/g/ecommerce 【参考方案1】:我在这里设计了一个基本模型
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
full_name = models.CharField(max_length=200)
joined_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.full_name
class ProductCategory(models.Model):
"""
storing product category to link with every product
a category like Fan, Refrigerator...etc
"""
name = models.CharField(max_length=200, db_index=True, verbose_name="product category")
def __str__(self):
return self.name
class Product(models.Model):
image_src = models.URLField(max_length=300,null=True, blank=True)
name = models.CharField(max_length=200, db_index=True, verbose_name="processor name")
category = model.ForeignKey(ProducyCategory,null=True,blank=True,on_delet=model.SET_NULL
brand = models.CharField(max_length = 300, null=True, blank=True)
....
def __str__(self):
return self.name
class CartItem(models.Model):
"""
Cart contain User and Product
"""
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
product = models.ForeignKey(Product,null=True,blank=True,on_delet=model.SET_NULL)
total = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "Cart: " + str(self.id)
【讨论】:
【参考方案2】:您应该为具有 image_src、名称和品牌字段的产品创建一个新模型。为不同的类别制作不同的模型是没有效果的。
【讨论】:
感谢您的回答。我为此使用了多表继承以上是关于如何在一个购物车中添加多个模型(Django)的主要内容,如果未能解决你的问题,请参考以下文章
如何从模型中获取一个项目并使用表单 django 将相同的项目保存在另一个模型中