Ace*_*ile 3 django django-admin
我有一个 Django 程序员的问题,应该很简单,但目前我不知道如何解决。
我有这三个模型(我尽可能地简化):
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)
Run Code Online (Sandbox Code Playgroud)
如您所见,Person 模型仅与 Cities 模型相关联。我需要做的是设置 PersonAdmin 类,以便在管理视图中添加一个显示 Nations.label 值的列并使其可搜索。在下面的示例中,我将此字段称为 city__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']
[...]
Run Code Online (Sandbox Code Playgroud)
我怎样才能让 Django 做到这一点?
提前谢谢!
向模型管理员添加一个方法,该方法接受一个人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']
Run Code Online (Sandbox Code Playgroud)
有关list_display更多信息,请参阅文档。
注意我已经用来list_select_related减少 SQL 查询的数量。
| 归档时间: |
|
| 查看次数: |
4699 次 |
| 最近记录: |