Displaying ForeignKey data in Django admin change/

2019-02-13 19:38发布

I'm trying to get an attribute of a model to show up in the Django admin change/add page of another model. Here are my models:

class Download(model.Model):
    task = models.ForeignKey('Task')

class Task(model.Model):
    added_at = models.DateTimeField(...)

Can't switch the foreignkey around, so I can't use Inlines, and of course fields = ('task__added_at',) doesn't work here either.

What's the standard approach to something like this? (or am I stretching the Admin too far?)

I'm already using a custom template, so if that's the answer that can be done. However, I'd prefer to do this at the admin level.

1条回答
乱世女痞
2楼-- · 2019-02-13 20:30

If you don't need to edit it, you can display it as a readonly field:

class DownloadAdmin(admin.ModelAdmin):
    readonly_fields = ('task_added_at',)

    def task_added_at(self, obj):
        return obj.task.added_at
查看更多
登录 后发表回答