2016-09-29 141 views
0

我對django程序員有一個問題,應該很容易,但目前我無法弄清楚如何解決。Django admin:list_display/search_fields外鍵在管理視圖中的外鍵

我有這三種模式(我簡化,就像我可以):

class Nations(models.Model): 
    label = models.CharField(max_length=200) 
    iso2 = models.CharField(max_length=2, unique=True) 

class Cities(models.Model): 
    label = models.CharField(max_length=200, null=True) 
    country_code = models.ForeignKey(Nations, to_field='iso2', on_delete=models.SET_NULL, null=True, verbose_name='Nation') 

class Person(models.Model): 
    username = models.CharField(max_length=200, blank=False) 
    city = models.ForeignKey(Cities, on_delete=models.SET_NULL, null=True, blank=True) 

正如你所看到的,人模型只是模型的城市連接。我需要做的是設置PersonAdmin類,以便在管理視圖中添加顯示Nations.label值的列並使其可搜索。在下面的例子中,我將這個field_country_code__label稱爲field_country_code__label,只是爲了讓你弄清楚我的意思(當然,因爲在Person模型中沒有country_code對象,所以它不起作用)。

class PersonAdmin(admin.ModelAdmin): 

    list_display = ('id', 'username', 'city', 'city__country_code__label') 
    ordering = ('username',) 
    raw_id_fields = ('city',) 
    search_fields = ['username', 'city__label', 'city__country_code__label'] 

[...] 

我怎樣才能讓Django做到這一點?

Thanx提前!

回答

2

向您的模特管理員添加一種方法,需要一個人obj並返回國家/地區標籤。然後將該方法添加到list_display

class PersonAdmin(admin.ModelAdmin): 
    def country_label(self, obj): 
     return obj.city.country_code.label) 

    list_display = ('id', 'username', 'city', 'country_label') 
    list_select_related = ['city__country_code'] 
    ordering = ('username',) 
    raw_id_fields = ('city',) 
    search_fields = ['username', 'city__label', 'city__country_code__label'] 

有關更多信息,請參閱list_display文檔。

注意我已經使用list_select_related來減少SQL查詢的數量。

+0

它很好用,謝謝阿拉斯代爾! –