Django里choices字段使用中文使用

如果想要将下面的表格里的内容数字换成对应的内容:

需要更改成这样:


下面是步骤:

在 python 里的 models.py 文件里,创建数据表的时候,用到了 choices

python 复制代码
class Example(models.Model):
    name = models.CharField(verbose_name="名称", max_length=32)
    price = models.IntegerField(verbose_name="价格")

    # 只适用于固定的选择
    category = models.SmallIntegerField(verbose_name="资产类型", choices=((1, '文具类'), (2, '3C类'), (3, '房产类')))

views.py 文件里,从数据库里获取数据,传给前端页面:

python 复制代码
def example_list(request):
    queryset = models.Example.objects.all().order_by("-id")

    return render(request, 'example_list.html', { "queryset": queryset })

example_list.html 文件里,做修改

html 复制代码
<table border="1px">
    <thead>
        <tr>
            <th>ID</th>
            <th>标题</th>
            <th>价格</th>
            <th>分类</th>
        </tr>
    </thead>
    <tbody>
        {% for obj in queryset %}
        <tr>
            <td>{{ obj.id }}</td>
            <td>{{ obj.name }}</td>
            <td>{{ obj.price }}</td>
            <td>{{ obj.get_category_display }}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>

在 html 里,得必须通过 obj.get_列表名称_display 的方法才能调用 choices 里的内容。

要想在 views.py 里,从数据库获取内容,可以通过

python 复制代码
# 必须得添加括号 ()
obj.get_列表名称_display() 

点个赞呗~

相关推荐
luckys.one1 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
大翻哥哥2 小时前
Python 2025:量化金融与智能交易的新纪元
开发语言·python·金融
言之。2 小时前
Django中的软删除
数据库·django·sqlite
zhousenshan3 小时前
Python爬虫常用框架
开发语言·爬虫·python
IMER SIMPLE4 小时前
人工智能-python-深度学习-经典神经网络AlexNet
人工智能·python·深度学习
CodeCraft Studio4 小时前
国产化Word处理组件Spire.DOC教程:使用 Python 将 Markdown 转换为 HTML 的详细教程
python·html·word·markdown·国产化·spire.doc·文档格式转换
weixin_456904274 小时前
Spring Boot 用户管理系统
java·spring boot·后端
专注API从业者5 小时前
Python/Java 代码示例:手把手教程调用 1688 API 获取商品详情实时数据
java·linux·数据库·python
java1234_小锋5 小时前
[免费]基于Python的协同过滤电影推荐系统(Django+Vue+sqlite+爬虫)【论文+源码+SQL脚本】
python·django·电影推荐系统·协同过滤
看海天一色听风起雨落5 小时前
Python学习之装饰器
开发语言·python·学习