2013-07-31 37 views
1

的問題,以顯示出現與此圖像 http://i.imgur.com/oExvXVu.png獲取的外鍵關係的對象在Django

使得VendorProfile名稱,而不是VendorProfile對象出現在框中我想它。我在VendorProfile中使用PurchaseOrder的外鍵關係。 這是我在models.py代碼:

class PurchaseOrder(models.Model): 
    product = models.CharField(max_length=256) 
    vendor = models.ForeignKey('VendorProfile') 
class VendorProfile(models.Model): 
    name = models.CharField(max_length=256) 
    address = models.CharField(max_length=512) 
    city = models.CharField(max_length=256) 

這裏是我的admin.py代碼:

class PurchaseOrderAdmin(admin.ModelAdmin): 
    fields = ['product', 'dollar_amount', 'purchase_date','vendor', 'notes'] 
    list_display = ('product','vendor', 'price', 'purchase_date', 'confirmed', 'get_po_number', 'notes') 

所以,我怎麼才能得到它在這兩個領域顯示VendorProfile的「名字」和list_display?

回答

3

定義一個__unicode__方法爲您的VendorProfile方法返回名稱。

從文檔:當你在對象上調用unicode()

__unicode__()方法被調用。 Django在很多地方使用unicode(obj)(或相關函數,str(obj))。最值得注意的是,在Django管理站點中顯示對象,並在顯示對象時將其作爲插入到模板中的值。因此,您應始終從__unicode__()方法中返回一個漂亮的,人類可讀的模型表示。

class VendorProfile(models.Model): 
    # fields as above 

    def __unicode__(self): 
     return self.name 
2

最簡單的方法是將Unicode功能添加到您的類返回要在下拉顯示的值:

class PurchaseOrder(models.Model): 
    product = models.CharField(max_length=256) 
    vendor = models.ForeignKey('VendorProfile') 

    def __unicode__(self): 
     return self.product 

class VendorProfile(models.Model): 
    name = models.CharField(max_length=256) 
    address = models.CharField(max_length=512) 
    city = models.CharField(max_length=256) 

    def __unicode__(self): 
     return self.name 

那麼這將在管理顯示供應商名稱落下。