Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to “list_display” in a Django ModelAdmin display attributes of ForeignKey fields?

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)
like image 643
TotuDoum Avatar asked Jan 14 '15 16:01

TotuDoum


1 Answers

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', ]

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

like image 155
dursk Avatar answered Oct 21 '22 06:10

dursk