2011-12-25 46 views
0

我正在爲網上商店製作購物車。我有一個像什麼是產品屬性的好模型

#Product 
from django.db import models 

class Product(models.Model): 
    title = models.CharField() 
    attribute = models.ManyToManyField('Attribute') 

我怎樣才能讓屬性模型,如大小,顏色與它們的鍵,如數字或選擇一個型號產品(「紅」,「綠」,......)?

回答

1

你讀過ManyToManyField嗎? https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField

您需要定義一個Attribute模型類指向,然後通過字段管理器的add方法添加關係。

class Attribute(models.Model): 
    value = models.CharField(max_length=64) 

class Product(models.Model): 
    title = models.CharField() 
    attribute = models.ManyToManyField('Attribute') 

product = Product.objects.create(title='foobar') 
red_attribute = Attribute.objects.create(value='Red') 
product.attribute.add(red_attribute)