2011-12-25 44 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)