Search code examples
djangodjango-tables2

How do i show an attribute of an object, rather than the object itself, in an accessor field in django-tables2?


I have a table of Compounds with a name field, which is linked to another table called Names.

When I render a table with django-tables2, it's showing up just fine except for the fact that it doesn't say aspirin in the name column, it says Name object.

models.py:

class Compound(models.Model):

    drug_id = models.AutoField(primary_key=True)

    drug_name = models.ForeignKey(Name, db_column='drug_name', null=True, on_delete=models.PROTECT)
    # for flagging problematic data
    flag_id = models.ForeignKey(Flag, db_column='flag_id', null=True, on_delete=models.PROTECT)
    # is a cocktail
    is_combination = models.BooleanField()

    class Meta:
        db_table = 'compounds'

tables.py:

import django_tables2 as tables
from .models import Compound

class FimTable(tables.Table):

    drug_name = tables.Column(accessor='name.name')

    class Meta:
        model = Compound
        attrs = {'class': 'paleblue table table-condensed table-vertical-center'}
        fields = ('drug_id', 'drug_name')
        sequence = ('drug_id', 'drug_name')
        order_by = ('drug_id')

views.py:

@csrf_protect
@login_required  # redirects to login page if user.is_active is false
def render_fim_table(request):

    table = FimTable(Compound.objects.all())

    table.paginate(page=request.GET.get('page', 1), per_page=20)

    response = render(request, 'fim_table.html', {'table': table})
    return response

Result:

The resulting table. Notice that it says "Name Object" instead of the name itself.


Solution

  • You just need to define the __str__ method on the Name object.

    class Name(models.Model):
        ...
    
        def __str__(self):
            return self.name