[Solved]-Django: foreign key value in a list display admin

25👍

Your Campaign model has no Company attribute – the ForeignKey is the field companyid. You’d need to change your function to

def related_company(self, obj):
    return obj.companyid.name
related_company.short_description = 'Company'

And since the __unicode__() method of the company object returns the name anyway, you probably don’t need the custom function anyway – I think you can put the foreign key field directly in the display list:

list_display = ['name', 'companyid', 'active', 'modified', 'created']
👤Blair

0👍

An additional feature to consider when you’re linking to a ForeignKey object in this way is to set related_company.allow_tags = True on the function.

This will make it so you can return HTML and have it be rendered as a usable link in the listview.

👤Jim K.

    Leave a comment