【问题标题】:Combining two columns into one using django_tables2使用 django_tables2 将两列合并为一列
【发布时间】:2016-06-30 06:34:17
【问题描述】:

我在 django_tables2 中有下表:

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

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

我想要的是有一个名称列,其中填充类似'lastname'+', '+firstname' 的内容,以便读取姓氏,可以按姓氏排序的名字。

The docs 建议这是可能的,但它没有给出将现有数据重用于新列的工作示例。只是更改现有数据。

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

【问题讨论】:

    标签: python django django-tables2


    【解决方案1】:

    像这样更新你的模型:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-09
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 1970-01-01
        • 2020-04-24
        相关资源
        最近更新 更多