Как это можно вызвать значения OneToOneField в админке, используя list_display = [] - PullRequest
2 голосов
/ 12 апреля 2020

моя модель

    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?

1 Ответ

3 голосов
/ 12 апреля 2020

Согласно PEP8 , имена классов обычно должны использовать соглашение CapWords .

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

также, чтобы показать username в 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)
...