1

我有以下代码:

模型.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)

管理员.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)

联合字段显示为列表,但选择菜单中的文本显示为“联合对象”。对于列表,我创建了一个函数来从相关联邦模型的翻译关系中获取数据。我想对表单字段做同样的事情。如果我让它在没有功能的表单字段中工作,我还将更改列表显示以同样的方式工作。

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

谢谢!

4

1 回答 1

1

默认情况下,它使用__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
于 2016-06-30T12:28:54.850 回答