[Answered ]-Combining two columns into one using django_tables2

1👍

Update your model like this:

class Customer(models.Model):
    # Fields

    @property
    def full_name(self):
        return '{0} {1}'.format(self.first_name, self.last_name)

and Update your Table class:

class CustomerTable(tables.Table):
    full_name = tables.Column(accessor='full_name', verbose_name='Full Name')
    class Meta:
        model = Customer
        attrs = {'class': 'table'}
        fields = {'lastname', 'firstname', 'businessname', 'entrydate', 'full_name'}
👤ruddra

1👍

I found a way to accomplish this without adding another property to your Model.

Use the first field as the accessor and format the second part into a render_() method. Ordering should be ok since you’re rendered value has the last name first.

class CustomerTable(tables.Table):

    lastname = tables.Column(verbose_name="Lastname, Firstname")

    class Meta:
        model = Customer
        attrs = {'class': 'table'}
        fields = {'lastname', 'businessname', 'entrydate'}

    def render_lastname(self, record, value):
        return mark_safe(f"{value}, {record.firstname}")
👤Ben

Leave a comment