您好我有产品型号,ProductColor和产品尺寸型号。我想正确地将产品与尺寸和颜色联系起来,例如我的用户在选择小尺寸的产品(Tshrit)时,它应该只显示那个小尺寸的可用颜色。
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2,max_digits=1000)
active =models.BooleanField(default=True)
weight = models.CharField(max_length=100, null=True, blank=True)
class ProductColor(models.Model):
product = models.ForeignKey(Product)
color = models.CharField(max_length=120)
active = models.BooleanField(default=True)
def __str__(self):
return self.color
def get_absolute_url(self):
return self.product.get_absolute_url()
CHOOSE_SIZE = (
('Extra Small', 'XS'),
('Small', 'S'),
('Medium', 'M'),
('Large', 'L'),
('Extra Large', 'XL'),
('Double Large', 'XXL'),
('Triple Large', 'XXXL'),
)
class ProductSize(models.Model):
product = models.ForeignKey(Product)
size = models.CharField(max_length=120, choices=CHOOSE_SIZE)
price = models.DecimalField(decimal_places=2, max_digits=20)
sale_price = models.DecimalField(decimal_places=2, max_digits=20, null=True, blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.size
def get_absolute_url(self):
return self.product.get_absolute_url()
<div class="col-sm-4">
<h3>{{ object.price }}</h3>
<!-- <select class="form-control">
{% for vari_obj in object.productsize_set.all %}
<option value="{{ vari_obj.id }}">{{ vari_obj }}
</option>
{% endfor %}
</select> -->
{% if object.variation_set.count > 1 %}
<h5>Size</h5>
<select class="form-control">
{% for vari_obj in object.productsize_set.all %}
<option value="{{ vari_obj.id }}">{{ vari_obj }}
</option>
{% endfor %}
</select>
{% endif %}
<br/>
<h5>Available Color</h5>
<select class="form-control">
{% for color_obj in object.productcolor_set.all %}
<option value="{{ color_obj.id }}">{{ color_obj }}
</option>
{% endfor %}
</select>
<a href="#">Add to cart</a>
<br/>
<hr/>
</div><!--end of col-sm-4!-->
谢谢你目前的情况问题是因为我没有正确地链接产品尺寸和颜色,当我添加红色衬衫大号,红色衬衫小和蓝色衬衫中等为同一产品。在我的产品detial页面Dropdwon的可用颜色大小如下:红色,红色,蓝色
答案 0 :(得分:1)
像这样创建一个名为ProductSizeColor的新模型
class ProductSizeColor(models.Model):
product = models.ForeignKey(Product)
color = models.ForeignKey(ProductColor)
size = models.ForeignKey(ProductSize)
现在当您将所有数据插入表格时,只需将产品,颜色和大小插入到ProductSizeColor模型中即可。如果您需要XL尺码汤姆T恤的所有颜色,请像这样搜索
ProductSizeColor.objects.filter(
product=tom_t_shirt_object,
size=XL_size_object_for_tom_t_shirt
)