【问题标题】:Can django-model-utils StatusModel provide human readable status options?django-model-utils StatusModel 可以提供人类可读的状态选项吗?
【发布时间】:2011-08-28 22:18:59
【问题描述】:

我正在尝试使用 Carl Meyer 的 django-model-utils 包中的 StatusModel feature 创建一个具有状态字段的模型。这是一个非常好的设计,您可以将模型从 StatusModel 子类化,并将 Choices 对象传递给模型上名为 STATUS 的字段,该字段会自动在数据库表示中创建“status”和“status_changed”字段。

我希望我的状态字段有一个单独的人类可读值而不是它的数据库表示,documentation for the Choices class 说它可以传递一个双元组,其中第一个值是选择的数据库表示第二个是人类可读的值。但是当我尝试使用上面的 Choices 对象对我的 StatusModel 执行此操作时,当我在模板中使用状态字段时,我仍然会得到数据库表示。

这是我的模型类的摘录:

from django.utils.translation import ugettext as _
from model_utils import Choices
from model_utils.models import StatusModel

STATUS_CHOICES = Choices(
    ('awaiting_approval', _('Awaiting approval')), 
    ('returned_to_submitter', _('Returned to submitter')), 
    ('approved', _('Approved')), 
    ('denied', _('Denied')),
)

class Petition(StatusModel):
    STATUS = STATUS_CHOICES
    ...

这是我的模板:

<table>
    <tr>
        <th>Status</th>
    </tr>
    {% for petition in petitions %}
    <tr>
        <td>{{ petition.status }}</td> 
        <!-- expecting "Awaiting approval" but it displays "awaiting_approval" -->
    </tr>
    {% endfor %}
</table>

如何让模型类返回人类可读的状态?还是StatusModel 不支持Choices 对象的那个特性?

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    您可以只使用普通的get_FOO_display() 方法——在本例中为{{ petition.get_status_display }}

    【讨论】:

    猜你喜欢
    • 2021-06-25
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多