Reputation: 93
I have the following table in django_tables2:
class CustomerTable(tables.Table):
class Meta:
model = Customer
attrs = {'class': 'table'}
fields = {'lastname', 'firstname', 'businessname', 'entrydate'}
My customer model has a firstname
and a lastname
field.
What I would like is to have a single Name column that populates with something like 'lastname'+', '+firstname'
so that it reads Lastname, Firstname sortable by last name.
The docs suggest that this is possible but it doesn't give a working example of reusing existing data into a new column. Just altering existing data.
How would I go about combining these two fields into a single column?
Upvotes: 1
Views: 2480
Reputation: 2547
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}")
Upvotes: 1
Reputation: 51988
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'}
Upvotes: 1