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() 

点个赞呗~

相关推荐
前端玖耀里44 分钟前
如何使用python的boto库和SES发送电子邮件?
python
serve the people44 分钟前
python环境搭建 (十二) pydantic和pydantic-settings类型验证与解析
java·网络·python
小天源1 小时前
Error 1053 Error 1067 服务“启动后立即停止” Java / Python 程序无法后台运行 windows nssm注册器下载与报错处理
开发语言·windows·python·nssm·error 1053·error 1067
喵手1 小时前
Python爬虫实战:HTTP缓存系统深度实战 — ETag、Last-Modified与requests-cache完全指南(附SQLite持久化存储)!
爬虫·python·爬虫实战·http缓存·etag·零基础python爬虫教学·requests-cache
喵手1 小时前
Python爬虫实战:容器化与定时调度实战 - Docker + Cron + 日志轮转 + 失败重试完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·容器化·零基础python爬虫教学·csv导出·定时调度
2601_949146532 小时前
Python语音通知接口接入教程:开发者快速集成AI语音API的脚本实现
人工智能·python·语音识别
寻梦csdn2 小时前
pycharm+miniconda兼容问题
ide·python·pycharm·conda
Java面试题总结3 小时前
基于 Java 的 PDF 文本水印实现方案(iText7 示例)
java·python·pdf
不懒不懒3 小时前
【决策树算法实战指南:从原理到Python实现】
python·决策树·id3·c4.5·catr
马猴烧酒.3 小时前
【面试八股|Java集合】Java集合常考面试题详解
java·开发语言·python·面试·八股