2013-07-24 18 views
-1

我創建了一個產品存儲區。如何在Django模型中執行「預設」

class Product(models.Model): 
    name = models.CharField(verbose_name=_(u'name'), max_length=200) 
    quantity = models.IntegerField(verbose_name=_(u'quantity')) 

>>> Product.objects.create(name="egg", quantity="100") 
>>> Product.objects.create(name="ham", quantity="10") 

現在我想創建食譜,如:從3個雞蛋和一片火腿炒雞蛋。 我試圖描述是這樣的:

class Recipe(models.Model): 
    name = models.CharField(verbose_name=_(u'name'), max_length=200) 
    items = models.ManyToManyField('Product', related_name='recipe_sets') 

但停留在描述所需要的產品數量爲一個recipe

我應該把quantity放在另一個模型中嗎?我如何計算份數(取決於產品的數量)?有沒有優雅的方式或申請扣除產品(由於烹飪一道菜)?

+0

這是不是一個真正的Django的問題。這是一個模式設計問題。您應該對訂單/產品/零件類型應用程序的模式設計進行一些研究,其中有很多應用程序。這會讓你走向正確的方向。 –

回答

1

你將需要另一張桌子。 ManyToMany將創建一個鏈接您擁有的兩個模型的中間表。但是,如果您更清楚地瞭解該表的創建方式,則可以將字段添加到鏈接表中。

請參閱文檔extra fields on many to many relationships。基本上,你就會有另一種模式:

class Ingredients(models.Model): 
    product = models.ForeignKey(Product) 
    recipe = models.ForeignKey(Recipe) 
    quantity = models.SomeField(..) 

,然後更改爲ManyToManyFieldRecipe定義:

items = models.ManyToManyField('Product', related_name='recipe_sets', through='Ingredients')