如何在 Django Admin 中显示父对象属性?

How could I display parent object attribute in Django Admin?

目前我正在开发电子商务应用程序。

它包含一个名为“博客”的子应用程序。 这个想法是超级用户为 *Trainer 创建一个帐户。 And yeah, I already created a new AbstractUser

培训师登录到他的帐户并创建 Post I logged in here using my Trainer`s credentials

在我想让超级用户看到 WHO 创建后 post,但 DjangoAdmin 显示我管理员的电子邮件

如何在 Django 管理中显示 post 的 'creator' 的电子邮件?

代码:

#models.py
class UserTrainer(AbstractUser):
    email = models.EmailField(verbose_name='email', max_length=100, unique=True)
    age = models.PositiveIntegerField(null=True)
    info = RichTextField(blank=True, null=True)
    image = models.ImageField(upload_to='media/stuff_images')
    inst = models.URLField(blank=True)
    REQUIRED_FIELDS = ['email', ]

    def __str__(self):
        return self.email

    def get_email(self):
        return self.object.email


class Post(models.Model):
    DEFAULT_TRAINER_ID = 1

    article = models.CharField(max_length=50, default='Article text')
    slug = models.SlugField(max_length=30)
    keywords = models.CharField(max_length=100)
    text = RichTextField(blank=True, null=True)
    trainer = models.ForeignKey(UserTrainer, on_delete=models.CASCADE, null=False, default=1)

    def __str__(self):
        return self.article

    class Meta:
        verbose_name = 'Post'
        verbose_name_plural = 'Posts'

#admin.py
class CustomUserAdmin(UserAdmin):
    model = UserTrainer
    add_form = CustomUserCreationForm
    fieldsets = (
        *UserAdmin.fieldsets,
        (
            'TrainerInfo',
            {
                'fields': (
                    'age', 'info', 'image', 'inst',
                )
            }
        )
    )

admin.site.register(UserTrainer, CustomUserAdmin)
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ('article', 'slug','trainer')
    list_display_links = ('article',)
    fields = ('article', 'slug', 'keywords', 'text',)
    readonly_fields = ('trainer',)

问题是您在保存 post 时没有指定用户,因此您应该覆盖 admin.py 中的保存方法,试试这个 (OFFICIAL DOCS):

admin.site.register(UserTrainer, CustomUserAdmin)
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ('article', 'slug','trainer')
    list_display_links = ('article',)
    fields = ('article', 'slug', 'keywords', 'text',)
    readonly_fields = ('trainer',)

    def save_model(self, request, obj, form, change):
        obj.trainer = request.user
        super().save_model(request, obj, form, change)