Django模型status字段显示数值而非描述文本的解决方法
解决Django Choices字段显示数值而非文本的问题
这是Django使用choices字段时的典型小坑——直接输出字段值只会拿到数据库里存储的数字,要显示对应的可读文本,你需要用Django自动为带choices的字段生成的get_<field_name>_display()方法。
具体修改步骤:
在你的article_list.html模板里,把原来的{{ article.status }}替换成{{ article.get_status_display }}就可以了。修改后的模板代码片段如下:
<table class="table table-bordered"> <tr> <th>Status</th> <th>Title</th> <th>Author</th> <th>Latest Updated</th> </tr> {% for article in articles %} <tr> <td>{{ article.get_status_display }}</td> <td>{{ article.title }}</td> <td>{{ article.author }}</td> <td>{{ article.date_updated }}</td> </tr> {% endfor %} </table>
原理说明:
当你在模型字段里定义了choices参数后,Django会自动为该模型实例添加一个名为get_<字段名>_display的方法(注意模板里调用时不需要加括号,Django模板引擎会自动处理方法调用)。这个方法会根据字段存储的数值,返回choices元组中对应的文本值——比如当status为0时返回normal,为-1时返回deleted。
如果是在视图或其他Python代码里需要获取这个文本,直接调用实例的方法即可:
article = Article.objects.get(pk=1) print(article.get_status_display()) # 输出对应的文本,比如'normal'
内容的提问来源于stack exchange,提问作者Wizard
相关产品推荐
相关产品推荐

