[Answer]-Django-tables2 reverse lookup

1๐Ÿ‘

A late answer, but here is what works for me in Django 1.8.6 with django-tables2 1.1.0 (based on Django-Tables2 Issue 156 and This answer). To access a one to many set of objects via a foreign key relation you need to just use the related_name in the accessor and then create a render method to produce what gets written to column cell. In that method you can then get all the foreign model objects and access their fields in a for loop.

class LeadTable(tables.Table):
    business_name = tables.LinkColumn('lead-detail', args=[A('slug')])
    updates = tables.Column(accessor='related_update')
    def render_updates(self, value, table):
        updates = ""
        uFirst = True
        updatesList = list(value.all())
        for u in updatesList:
            if not uFirst:
                updates += ", "
            else:
                uFirst = False
            updates += u.update
        return updates
    class Meta:
        model = lead
        fields = ("business_name","first_name", "last_name","number_of_pos","submission_date","updates")
        attrs = {"class":"paleblue"}
๐Ÿ‘คSteve

0๐Ÿ‘

according to django docs

in your views you can access them in this way (assuming lead_instance is an instance of lead class):

all_leadtables_for_lead = lead_instance.leadtable_set

a side note: use Capitalized names for classes (class Lead(models.Model):) in order to adhere to python PEP8 guidelines.

๐Ÿ‘คfurins

Leave a comment