list_display包含外键的模型

时间:2013-12-06 15:13:23

标签: django django-admin

我有以下django模型。 在TestCase表的django管理模型中,在list_display中,我想显示最新评论和Remark表的修饰名称。

models.py

from django.db import models

class Release(models.Model):
    title        = models.CharField(max_length=128)
    start_time   = models.DateField('Release Start Date')
    release_date = models.DateField('Release Ended Date')

    def __str__(self):
        return self.title

class TestCase(models.Model):
    query       = models.CharField(max_length=256)
    ksq_id      = models.IntegerField()
    status      = models.CharField(max_length=64)
    release     = models.ForeignKey(Release) # Release can have many test cases

    def __str__(self):
        return self.query

class Remark(models.Model):
    owner       = models.CharField(max_length=64)
    module      = models.CharField(max_length=64)
    comment     = models.CharField(max_length=1024)
    modified_ts = models.DateTimeField('date modified', auto_now=True)
    modifier    = models.CharField(max_length=64)
    testcase    = models.ForeignKey(TestCase) # Testcase can have many Re

admin.py

from django.contrib import admin
from kramer_release.models import Release, TestCase, Remark

class RemarksInline(admin.TabularInline):
    model = Remark
    extra = 0 

class RemarkAdmin(admin.ModelAdmin):
    list_display = ('owner', 'module', 'testcase_query')

    def testcase_query(self, obj):
        return obj.testcase.query

class TestCaseAdmin(admin.ModelAdmin):
    inlines = [RemarksInline]
    list_display = ('query', 'status')

admin.site.register(Release)
admin.site.register(TestCase, TestCaseAdmin)
admin.site.register(Remark, RemarkAdmin)

1 个答案:

答案 0 :(得分:0)

您可以定义一个函数来获取最新评论作为管理类的一部分,例如:

class TestCaseAdmin(admin.ModelAdmin):
    inlines = [RemarksInline]
    list_display = ('query', 'status', 'latest_comment')

    def latest_comment(self, obj):
        remarks = Remark.objects.filter(testcase=obj).order_by('-modified_ts')
        if remarks:
            return '%s - %s' % (remarks[0].comment, remarks[0].modifier)
        return None

see the docs