Django e-commerce part14 Product Variations
Product Variationのmodelを作る
Variationは、例えば、iphone7 16GB,32GBとか言うように、同じ商品で、別々のvariationがある場合 * products/models.py に、以下を追加する。
class Variation(models.Model): product = models.ForeignKey(Product) title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=0, max_digits=20) active = models.BooleanField(default=True) inventory = models.IntegerField(null=True, blank=True)#refre none== unlimited amount
IntegerFIieldには、nagativeとpositiveがある。 多分、正の整数と、負の整数という意味だと思う。在庫はpositiveのため、特に設定しなければ、positiveになる。
- さらに、Variationにmethodを追加していく
class Variation(models.Model): product = models.ForeignKey(Product) title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=0, max_digits=20) sale_price = models.DecimalField(decimal_places=0, max_digits=20, null=True, blank=True) active = models.BooleanField(default=True) inventory = models.IntegerField(null=True, blank=True)#refre none== unlimited amount def __str__(self): return self.title def get_price(self): if self.sale_price is not None: return self.sale_price else: return self.price def get_absolute_url(self): return self.product.get_absolute_url()
get_priceは、sale_priceがある時に、sale_price, ない時は、priceを返すmethod
get_absolute_urlは、Productのget_absolute_urlをゲットするリスト。
- product_detail.htmlに設定する。
product_detail.html
{% extends "base.html" %} {% block content %} {{ object.title }} {{ object.variation_set.all }} {% endblock %}
{{ object.variation_set.all }}は、objectのforeignkeyが関連づけられているテーブルのVariationのquerysetを全部ゲットするという感じの意味。これだとcontextとかで渡さなくても、objectからメソッドで、よびだせる。
- そのため、以下のような設定も可能。 optionvalueというのは、選択肢が出てくるtagの事
{% extends "base.html" %} {% block content %} {{ object.title }} {{ object.id }} <select class='form-control'> {% for vari_obj in object.variation_set.all %} <option value="{{ vari_obj.id }}">{{ vari_obj }}</option> {% endfor %} </select> {% endblock %}
- Variationは、最初なんで作るのかよくわからなかった。goalがわかっておくのは非常に大事だね。