[Answered ]-In Django Tables2, how do you make a column show text from a table referenced by a foreign key?

1👍

I’ve been struggling to get something working too (but I finally did), and I found the examples too brief.

I think you want to get rid of this stuff in the Meta class

"instrument__instrumenttype_id__instrumenttypes__id_instrumentType" 

I think Meta.fields should just be a list of field names, and that you refer to the attribute in the other table from the point of view of the type of object you will later pass in to the IntrumentTable constructor (and that is named in the Meta.model attribute:

from django_tables2.utils import Accessor

class InstrumentTable(tables.Table):
    instrument_type = tables.Column(accessor=Accessor('instrumenttype.name'))
            
    class Meta:
        model = Instrument
        template_name = "django_tables2/bootstrap.html"
        fields = ("id", "instrument", "nickname", "serialNo", "instrument_type")

Then, in view, make an instance of InstrumentTable

def myview(request):
    table_to_render = InstrumentTable(Instrument.objects)
    return render(request, sometemplate, {table: table_to_render})

You didn’t show your view, and I know there may be a different way. If you have the whole thing in a repo somewhere, leave a link.

Leave a comment