如何在PARENT管理员页面上显示ForeignKey模型的下拉列表

时间:2019-04-25 06:53:08

标签: python django model admin

似乎无法弄清楚。我有一个模型-Show和Episode,它与Show具有ForiegnKey关系。在“显示管理员”页面上,我想要所有情节的下拉显示,这些内容都将链接到其“管理员模型”页面...我唯一能得到的是折叠形式的只读形式。我喜欢与此相关的指向管理页面的链接,但我只希望在下拉菜单中提供它。

***models.py***
class Show(models.Model):
    title = models.CharField(_("title"), null=True, max_length=5000)
    slug = models.SlugField(_("slug"),  max_length=5000, unique=True)

class Episode(models.Model):
    show = models.ForeignKey(Show, verbose_name=_("show"), on_delete=models.CASCADE)
    title = models.CharField(_("title"), null=True, max_length=5000)
***admin.py***
class ShowAdmin(admin.ModelAdmin):
    list_display = ('title', 'get_latest_duration', 'get_latest_pub_date',)
    inlines = [
        EpisodeInline,
    ]

class EpisodeInline(admin.StackedInline):
    model = Episode
    fieldsets = (
        ('Episodes', {
            'classes': ('collapse',),
            'fields': ('title',),
        }),)

1 个答案:

答案 0 :(得分:0)

您可以使用只读字段。这是一个示例:

from django.contrib import admin

class ShowAdmin(admin.ModelAdmin):
    readonly_fields = ('episode_list',)

    def episode_list(self, instance):
        # you may render a html list here with episode names
        return ",".join([x.name for x in instance.episodes]) # replace episodes with your model's related name

在此处查看示例:https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields