Django_tables2 class 定义中的条件语句

Conditional statements in Django_tables2 class definition

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

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”时,它似乎是 return 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>

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

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": ""
            }

您只需修改返回 table class 值的方式。

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
    }

您似乎也没有正确比较值,需要改用双等号。