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提前!
它很好用,謝謝阿拉斯代爾! –