如何在Django ModelAdmin中“list_display”显示ForeignKey字段的属性?

时间:2015-01-14 16:29:15

标签: python django foreign-keys admin

我遇到了与他完全相同的问题:Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

我想在答案管理员上看到问题。 我做了与答案相同的事情,但得到了这个错误:

'Answer' object has no attribute 'question'

这是我的代码(问题可以有很多可能的答案):

class Question(models.Model):
    question = models.CharField(max_length=255)


class Answer(models.Model):
    question = models.ForeignKey('Question')
    answer = models.CharField(max_length=255)

我的管理员:

class AnswerAdmin(admin.ModelAdmin):
    model = Answer
    list_display = ['answer', 'get_question', ]

    def get_question(self, obj):
        return obj.question.question


admin.site.register(Answer, AnswerAdmin)

1 个答案:

答案 0 :(得分:5)

不确定为什么这不起作用,但另一种解决方案是覆盖__unicode__()中的Question方法(如果您使用的是Python3,则为__str__()),这是在ForeignKey中包含list_display字段时显示的内容:

class Question(models.Model):
    question = models.CharField(max_length=255)

    def __unicode__(self):
        return self.question


class Answer(models.Model):
    question = models.ForeignKey('Question')
    answer = models.CharField(max_length=255)

class AnswerAdmin(admin.ModelAdmin):
    model = Answer
    list_display = ['answer', 'question', ]

文档:https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display