繁体   English   中英

使用 django_tables2 将两列合并为一列

[英]Combining two columns into one using django_tables2

我在 django_tables2 中有下表:

class CustomerTable(tables.Table):
    class Meta:
        model = Customer
        attrs = {'class': 'table'}
        fields = {'lastname', 'firstname', 'businessname', 'entrydate'}

我的客户模型有一个firstname和一个lastname字段。

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

文档表明这是可能的,但它没有给出将现有数据重用于新列的工作示例。 只是改变现有数据。

我将如何将这两个字段合并到一个列中?

像这样更新你的模型:

class Customer(models.Model):
    # Fields

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

并更新您的 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'}

我找到了一种无需向模型添加其他属性即可完成此操作的方法。

使用第一个字段作为访问器并将第二部分格式化为render_()方法。 排序应该没问题,因为您呈现的值首先是姓氏。

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