Search code examples
pythondjangodjango-tables2

Django tables2 add custom column for another model


I don't know if this question had been covered or not yet, I searched all the related questions but I couldn't find a solution.

What I want to do is to create a table using django-tables2 with a model let's say model A, and I want to add a custom column to this table having value from model B which is not related in any case to model A.

This is what I did


class TableA(tables.Table):
  
    class Meta:
        model = A
        template_name = "django_tables2/bootstrap.html"
        fields = ("id","username","data_from_b")



Where can I put the B.objects.filter() to append it's data to a custom column.

Your help would be appreciated. Thanks.


Solution

  • You can use a custom render method to retrieve anything you need.

    https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html#table-render-foo-methods

    For example, a list of B names could look like:

    from django.utils.safestring import mark_safe
    
    class TableA(tables.Table):
    
        data_from_b = tables.Column()
    
        class Meta:
            model = A
            template_name = "django_tables2/bootstrap.html"
            fields = ("id","username","data_from_b")
        
        def render_data_from_b(self, value, record):
            return mark_safe("</br>".join(B.objects.filter().values_list("name", flat=True)))