1、get_FOO_display 介绍

在 Django 框架中,get_FOO_display() 方法是用来查找模型中的 choice 值的,比如说我们在模型中定义了一个字段,并且这个字段的值是受限的,我们可以使用 get_FOO_display() 方法来查找这个字段的值。例如,我们定义了一个字段名为 status,其值有三个可选项:active,inactive 和 disabled,那么我们可以使用 get_status_display() 方法来查找 status 字段的值。

2、get_FOO_display 使用说明

get_FOO_display() 方法非常简单易用,只需要在模型中定义一个 choice 字段,并且指定其值,然后使用 get_FOO_display() 方法来查找字段的值即可。例如,我们定义了一个字段名为 status,其值有三个可选项:active,inactive 和 disabled,那么我们可以使用 get_status_display() 方法来查找 status 字段的值,具体使用方法如下:

123
status = models.CharField(
    max_length=20,
    choices=[
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('disabled', 'Disabled'),
    ],
    default='active',
)

status_display = model_instance.get_status_display()
Python

上面的代码中,我们定义了一个字段 status,并且指定了三个可选项:active,inactive 和 disabled,然后我们使用 get_status_display() 方法来查找 status 字段的值,即可得到 status 字段的值。

3、get_FOO_display 使用注意事项

使用 get_FOO_display() 方法查找模型中的 choice 值时,有以下几点需要注意:

1、首先,我们需要在模型中定义一个 choice 字段,并指定其可选项;

2、然后,使用 get_FOO_display() 方法来查找字段的值,其中 FOO 为字段名;

3、最后,我们可以得到字段的值。