django admin changelist来自froreignKey的foreignKey可排序

时间:2013-02-13 17:18:21

标签: django django-admin

我有这个型号:

class Project(models.Model):
    name = models.CharField()

class Task(models.Model):
    title = models.CharField()
    project = models.ForeignKey('Project')

class Activity(models.Model):
    title = models.CharField()
    task = models.ForeignKey('Task')

在Activity的更改列表中我想显示一个包含Project.name的列。是否可以显示内容并使此列可排序

1 个答案:

答案 0 :(得分:1)

class ActivityAdmin(admin.ModelAdmin):
    list_display = [
        'title',
        'task',
        'project',
    ]

    def project(self, obj):
        return obj.task.project.name

    project.admin_order_field = 'task__project__name'

admin.site.register(Activity, ActivityAdmin)