Django Admin 如何更改关系字段中的文本

Django Admin how to change text in relations field

我有以下代码:

models.py

from django.db import models
from parler.models import TranslatableModel, TranslatedFields

class Federation(TranslatableModel):
    translations = TranslatedFields(
        name = models.CharField('name', max_length=50)
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Athlete(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    federation = models.ForeignKey('Federation', on_delete=models.SET_NULL, null=True)
    height = models.IntegerField();
    weight = models.IntegerField();
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

admin.py

from django.contrib import admin
from parler.admin import TranslatableAdmin

from .models import Athlete, Federation

class AthleteAdmin(admin.ModelAdmin):
    list_display = ['first_name', 'last_name', 'height', 'weight', 'get_federation_name']
    fields = ['first_name', 'last_name', 'height', 'weight', 'federation']

    def get_federation_name(self, obj):
        obj.federation.set_current_language('en')
        return obj.federation.name
    get_federation_name.short_description = 'Federation'

class FederationAdmin(TranslatableAdmin):
    search_fields = ['translations__name']
    list_display = ['name']
    fields = ['name']

admin.site.register(Federation, FederationAdmin)
admin.site.register(Athlete, AthleteAdmin)

联合字段显示为列表,但 select 菜单中的文本显示为 "Federation object." 对于列表,我创建了一个函数来从相关联合模型的翻译关系中获取数据.我想对表单域做同样的事情。如果我让它在没有功能的表单字段中工作,我也会更改列表显示以同样的方式工作。

我是 Python 和 Django(第一次)的新手,我似乎找不到解决这个问题的方法。

谢谢!

默认使用对象的__str__()方法。所以改变这个最简单的方法就是设置这个方法。例如:

class Federation(models.Model):
    ...

    def __str__(self):
        return "{0} ({1})".format(self.translation, self.created_at)

另一种方法 — 如果您不想覆盖 __str__ 方法 — 将覆盖表单字段本身的 label_from_instance。但这更棘手。

def _federation_label_from_instance(self, obj):
    return "{0} ({1})".format(obj.translation, obj.created_at)

class AthleteAdmin(admin.ModelAdmin):
    ...

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        formfield = super().form_field(db_field, request, **kwargs)
        if db_field.name == 'federation':
            formfield.label_from_instance = _federation_label_from_instance
        return formfield