在django_tables2中为表添加额外的列

时间:2018-01-31 06:50:38

标签: django django-tables2

我想添加不在我模型中的额外列。我在此网站上将one of the solutions应用于我的项目。但它没有正常工作。

model.py

class Companies(models.Model):

    legal_name      = models.CharField(max_length=120, blank=True)
    co_name         = models.CharField(max_length=120, blank=True)
    client          = models.ForeignKey(Clients, models.SET_NULL, blank=True, null=True)
    tel_no          = models.CharField(max_length=120, blank=True)
    email           = models.EmailField(null=True, blank=True)
    address         = models.TextField(null=True, blank=True)
    contact         = models.CharField(max_length=250, blank=True)
    con_tel_no      = models.CharField(max_length=120, blank=True)
    entity          = models.CharField(max_length=2, null=True)
    yearend         = models.DateField(null=True, blank=True)
    bn              = models.CharField(max_length=9)
    memo            = models.TextField(null=True, blank=True)
    slug            = models.SlugField(null=True, blank=True)

    def t2_due_date(self):
        now_year = datetime.date.today().year
        if self.entity == 'CO':
            yearend_ = DateWidget.decompress(self, self.yearend)
            if yearend_[1] > 6:
                yearend_[2] = now_year + 1
                yearend_[1] -= 6
            else:
                yearend_[2] = now_year
                yearend_[1] += 6
            t2_due = DateWidget.compress(self, yearend_)
        return t2_due

tables.py

class ScheduleTable(tables.Table):
    due_date_col = tables.Column(accessor='t2_due_date', verbose_name='T2 Due Date')

    class Meta:
        attrs = {"class": "paleblue", "width":"100%"}
        fields = ['client','legal_name', 'co_name', 'entity', 'yearend', 'due_date_col']
        model = Companies

当我运行此程序' due_date_col'总是空白的。似乎功能(' t2_due_date)没有通过。你有什么线索可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

据我所知accessor指向相关对象,而不是模型的属性,方法等。

您可以尝试使用Table.render_{column}

class ScheduleTable(tables.Table):

    def render_due_date_col(self, record):
        return record.t2_due_date()

有关详细信息,请参阅djanog tables official doc