django-tables2: Adding a new custom column not found in model

做~自己de王妃 提交于 2019-12-13 00:14:48

问题


I have the following table:

class TaskTable(tables.Table):

    def render_foo(self):
        raise Exception()

    class Meta:
        model = Task
        fields = ['foo']

for the following model:

class Task(models.Model):
    priority = models.PositiveIntegerField()
    title = models.CharField(max_length=1024)
    content = models.TextField(null=True, blank=True)

According to the docs, render_foo won't be executed if it is considered an empty value.

My requirement is that foo is not found in the Model. How can I implement the column foo?


回答1:


You have to pass an empty_values=() keyword argument to the column, to quote the docs:

render methods are only called if the value for a cell is determined to be not an empty value. When a value is inColumn.empty_values, a default value is rendered instead (both Column.render and Table.render_FOO are skipped).

In your case, the 'value' for your non-existing column is None, so if that value is in empty_values, the default value (- by default is rendered).

So in code, it could look like this:

class TaskTable(tables.Table):
    foo = tables.Column(empty_values=())

    def render_foo(self):
        raise Exception()

    class Meta:
        model = Task

relevant docs



来源:https://stackoverflow.com/questions/50477741/django-tables2-adding-a-new-custom-column-not-found-in-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!