2015-02-09 70 views
0

SQL查詢的結果我有2種型號:的Django與python3,在選擇框

PR_Components (models.Model): 
    companyID = models.ForeignKey(PO_Company, blank=True, null=True) 
    comp_nr = models.CharField (max_length=5, blank=True, null=True) 

    def __str__(self): 
     return self.comp_nr 

PR_ComponentsData (models.Model): 
    compID = models.ForeignKey (PR_Components, blank=False, null=True) 
    valid = models.DateField (max_length=10, blank=False, null=True) 
    comp_image = models.ImageField (upload_to="/images", blank=True, null=True) 
    comp_text = models.CharField (max_length=30, blank=False, null=True) 
    .... 

我想在一個選擇框,現在中顯示的組件數量(PR_Components.comp_nr)和當前有效的名稱(PR_Componentsdata.comp_text )。

我添加了一個管理器來建模PR_Components執行SQL查詢。

SELECT a.*, b1.* FROM pool_pr_components a 
JOIN pool_pr_componentsdata b1 ON (a.id = b1.compID_id) 
LEFT OUTER JOIN pool_pr_componentsdata b2 
ON (a.id = b2.compID__id AND (b1.valid < b2.valid OR b1.valid = b2.valid  
AND b1.id < b2.id)) WHERE b2.id IS NULL 

後來我寫的形式動態地和SQL-結果添加到字段:

self.fields[field].queryset = sql_result 

直到這裏,一切工作正常。

我的問題: 在模型PR_Components的海峽 - 方法的結果顯示(= comp_nr)的選擇框,但我想也顯示組件名稱,如「組件(001)」。

我該怎麼做?它應該是一個適用於其他模型的解決方案,因爲我的很多模型都有「歷史」數據。

非常感謝

回答

0

解決方案: 模型PR_Components我們覆蓋海峽

def __str__(self): 
    related = PR_ComponentsData.objects.filter(id=self.id).last() 
    return "{} ({})".format (related.comp_text, self.comp_nr)