Reputation: 137
I've got the exact same problem than him : Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
I want to see the question on the answer admin. I did the same thing than in the answer but got this error:
'Answer' object has no attribute 'question'
here is my code(question can have many possible answer):
class Question(models.Model):
question = models.CharField(max_length=255)
class Answer(models.Model):
question = models.ForeignKey('Question')
answer = models.CharField(max_length=255)
my admin:
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)
Upvotes: 6
Views: 7943
Reputation: 4445
Not sure why this wouldn't work, but an alternative solution would be to override the __unicode__()
method in Question
(or __str__()
if you're using Python3), which is what is displayed when you include a ForeignKey
field in 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', ]
Upvotes: 6