我想创建一个Django Web应用程序,用户可以在其中添加项目到购物车。
没有模型Colour
和Size
这到目前为止工作。
我的问题是,我无法弄清楚如何以正确的方式实现配置选项(例如)Colour
和Size
。
我添加了两个“选项”与多对一关系。我现在可以为产品添加多种颜色和尺寸,但不知道如何在CartEntry
中保存选择的“选项”
这是我到目前为止所得到的:
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
name = models.CharField(max_length=256)
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return str(self.name)
class Colour(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="rel_colour")
option = models.CharField(max_length=24)
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return str(self.colour)
class Size(models.Model):
product =models.ForeignKey(Product, on_delete=models.CASCADE, related_name="rel_size")
option = models.CharField(max_length=24)
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return str(self.size)
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)
def __str__(self):
return str(self.id) + ' - ' + str(self.user)
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.quantity) + ', ' + str(self.product.name)
也许我不能在这里为CartEntry
用户关系?
为什么不这样做:
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
name = models.CharField(max_length=256)
colour = models.ForeignKey(Colour, on_delete=models.CASCADE)
size = models.ForeignKey(Size, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return str(self.name)
class Colour(models.Model):
name = models.CharField(max_length=24)
def __str__(self):
return str(self.name)
class Size(models.Model):
name = models.CharField(max_length=24)
def __str__(self):
return str(self.name)
所以每种产品都有不同的颜色和大小。或者如果你想把一个产品作为“父”,你可以添加另外一个模型,比如说VariantProduct
class Product(models.Model):
name = models.CharField(max_length=256)
def __str__(self):
return str(self.name)
class VariantProduct(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
name = models.CharField(max_length=256)
colour = models.ForeignKey(Colour, on_delete=models.CASCADE)
size = models.ForeignKey(Size, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return str(self.name)