简体   繁体   English

使用 django_tables2 将两列合并为一列

[英]Combining two columns into one using django_tables2

I have the following table in django_tables2:我在 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.我的客户模型有一个firstname和一个lastname字段。

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.我想要的是有一个 Name 列,其中填充了诸如'lastname'+', '+firstname'之类的内容,以便它读取姓氏、名字,可按姓氏排序。

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:并更新您的 Table 类:

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.使用第一个字段作为访问器并将第二部分格式化为render_()方法。 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}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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