2013-01-15 57 views
1

我對Django來說是新的,我想實現以下目標:我有兩個表之間的關係,比如表B有一個ManyToMany引用表A.現在我想要一個表將選項保存到A &之間的特定組合的選項B.如何實現此目的?Django點ForeignKey到現有關係表

謝謝!

Hidde

回答

5

使用through選項ManyToMany場,並添加關係本身的信息。

例如

class Ingredient(models.Model): 
    name = models.TextField() 

class Recipe(models.Model): 
    name = models.TextField() 
    ingredients = models.ManyToManyField(Ingredient, through='RecipePart') 

class RecipePart(models.Model) 
    recipe = models.ForeignKey(Recipe) 
    ingredient = models.ForeignKey(Ingredient) 
    amount = models.IntegerField() 

# ... 
RecipePart(recipe=pizza, ingredient=cheese, amount=9001).save() 

如果關係已經存在(並且你已經有了數據),則必須更新數據庫模式(和創建模型,如果你使用自動映射)。 South可以幫助你做到這一點。

+0

感謝您的快速回復! –