簡體   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