如何使用 list_display=[] 在管理员中调用 OneToOneField 值

How is this possible to call OneToOneField values in admin using list_display=[]

我的模型

    class user_profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    age = models.IntegerField()

    profile_created = models.DateTimeField(auto_now_add=True, auto_now=False)
    timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)

admin.py

class UserProfileAdmin(admin.ModelAdmin):
list_display = ['user','user.username','profile_created', 'timestamp']
admin.site.register(user_profile, UserProfileAdmin)

它显示以下错误:

ERRORS: <class 'testapp.admin.UserProfileAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'user.username', which is not a call able, an attribute of 'UserProfileAdmin', or an attribute or method on 'testapp.user_profile'.

如何在 admin.py 中获取另一个 table 值?

根据 PEP8,class 名称通常应使用 CapWords 约定。

class <b>UserProfile</b>(models.Model):
    # your code

此外,要在 DjangoAdmin 中显示 用户名,您应该定义一个方法,

from django.core.exceptions import ObjectDoesNotExist


class UserProfileAdmin(admin.ModelAdmin):
    list_display = ['user', <b>'username',</b> 'profile_created', 'timestamp']

    <b>def <b>username</b>(self, instance): # name of the method should be same as the field given in `list_display`
        try:
            return instance.user.username
        except ObjectDoesNotExist:
            return 'ERROR!!'</b>

admin.site.register(<b>UserProfile</b>, UserProfileAdmin)