简体   繁体   中英

Combining two columns into one using django_tables2

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?

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'}

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}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM