【问题标题】:Conditional statements in Django_tables2 class definitionDjango_tables2 类定义中的条件语句
【发布时间】:2021-02-19 13:48:02
【问题描述】:

我正在尝试根据我的一个对象值更改表格行的格式。我知道如何将行属性传递给我的模板,但在决定我的行在类定义中的外观时不知道如何使用当前记录。见下文:

class OrderTable(tables.Table):
    my_id = tables.Column(verbose_name="Order number")
    status = tables.Column(verbose_name="Order status")

    class Meta:
        model = Order

        row_attrs = {
            "class": lambda record: record.status
        }

这是我在 django_tables2 文档中读到的内容。但是-当尝试添加一些“if”时,它似乎返回 lambda 函数对象而不是值:

class OrderTable(tables.Table):
    my_id = tables.Column(verbose_name="Order number")
    status = tables.Column(verbose_name="Order status")

    class Meta:
        model = Order

        print(lambda record: record.status)

        if lambda record: record.status = '0':
            row_attrs = {
                "class": "table-success"
            }
        else:
            row_attrs = {
                "class": ""
            }

我的日志中打印的是:<function ZamTable.Meta.<lambda> at 0x000001F7743CE430>

我也不知道如何使用“记录”属性创建自己的函数。我应该将什么传递给我新创建的函数?

class OrderTable(tables.Table):
    my_id = tables.Column(verbose_name="Order number")
    status = tables.Column(verbose_name="Order status")

    class Meta:
        model = Order

        def check_status(record):
            record = record.status
            return record

        status = check_status(???)

        if status = '0':
            row_attrs = {
                "class": "table-success"
            }
        else:
            row_attrs = {
                "class": ""
            }

【问题讨论】:

    标签: django django-tables2


    【解决方案1】:

    您只需要修改返回表类值的方式。

    row_attrs = {
        "class": lambda record: "table-success" if record.status == "0" else ""
    }
    

    或作为函数

    def calculate_row_class(**kwargs):
        """ callables will be called with optional keyword arguments record and table 
        https://django-tables2.readthedocs.io/en/stable/pages/column-attributes.html?highlight=row_attrs#row-attributes
        """
        record = kwargs.get("record", None)
        if record:
            return record.status
        return ""
    
    class Meta:
        model = Order
    
        row_attrs = {
            "class": calculate_row_class
        }
    

    看起来您没有正确比较值,需要改用双等号。

    【讨论】:

    • 我有一些“elif”要写,但我设法通过一些嵌套来处理它。有什么方法可以使用标准函数,而不是 lambda?
    • @Jorhanc - 添加了第二个使用函数的示例
    猜你喜欢
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 2012-03-09
    • 1970-01-01
    相关资源
    最近更新 更多