2013-10-21 130 views
-3

我有一個table1,帶有col_a,col_b,col_c,col_c。我有另一個table2,用tb_col1,tb_col2,tb_col3,我想引用col_a - > tb_col,col_b - > tb_col2,col_c - > tb_col3。來自一個表的多個外鍵

我應該使用組合鍵,如果是的話我如何在Django(蟒蛇)

我的模型實現這一點:

class product_models(models.Model): 
    products = models.ForeignKey('products') 
    model_name = models.CharField(max_length=50) 
    model_price = models.IntegerField(max_length=4) 
    model_desc = models.TextField(blank=True) 
    commision = models.IntegerField(max_length=3) 

    def __unicode__(self): 
     return self.model_name 



class sales_process(models.Model): 

    prospect = models.ForeignKey('prospect') 
    employee = models.ForeignKey(User) 
    first_call = models.DateTimeField 
    product = models.ForeignKey('products') 
    model_name = models.ForeignKey('product_models') 
    #price = reference to product_model for the price 
    #commission = reference to product_model for commission 

在這裏,我怎麼可以參考priceproduct_modelscommissionproduct_models

+0

查看Django文檔中的[模型層](https://docs.djangoproject.com/en/1.5/#the-model-layer)。用您試圖開發的代碼來編輯您的問題以實現您的表格,然後您可能有更好的機會獲得幫助。 –

+0

@Joseph Paetz爲了更加清晰,我已經更新了這個問題 – rakesh

回答

0

爲什麼不直接將sales_process關聯到product_models,如下所示:

product_model = models.ForeignKey('product_models')

沒有必要在sales_process模型上覆制product_models中的多個列嗎?

此外,看一看定製的型號經理: https://docs.djangoproject.com/en/dev/topics/db/managers/

您可以創建一個模型,方便的方法(說查找從相關模型的東西)的一個很好的方式命名。

在下面的示例中,您可以調用Team.objects.get(pk = 1).games()爲團隊返回所有遊戲,主或離開。

class TeamManager(models.Manager): 
    def games(self, name): 
     return Game.objects.filter(home__name=name) | Game.objects.filter(away__name=name) 


class Team(models.Model): 
    objects = TeamManager() 
    name = models.CharField(max_length=100, unique=True) 

class Game(models.Model): 
    away = models.ForeignKey(Team, null=True, blank=True, related_name="away") 
    home = models.ForeignKey(Team, null=True, blank=True, related_name="home") 
+0

這是一個很好的觀點。但是爲了這個緣故,如果我仍然想要重複一次,該怎麼辦? – rakesh

+0

我真的不認爲你想這樣做。你能解釋爲什麼你認爲這是必要的嗎? – mconlin

+0

我打算把'sales_process'作爲數據庫視圖,在那裏我創建表格,但是輸入連接兩個表格。 – rakesh