how to “list_display” in a Django ModelAdmin display attributes of ForeignKey fields?
我和他有一个完全相同的问题:Django ModelAdmin中的"List_Display"能否显示ForeignKey字段的属性?
我想看一下回答管理员的问题。我做了与答案相同的事情,但得到了这个错误:
1 | 'Answer' object has no attribute 'question' |
这是我的代码(问题可以有很多可能的答案):
1 2 3 4 5 6 7 | class Question(models.Model): question = models.CharField(max_length=255) class Answer(models.Model): question = models.ForeignKey('Question') answer = models.CharField(max_length=255) |
号
我的管理员:
1 2 3 4 5 6 7 8 9 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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_显示