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

点个赞呗~

相关推荐
gCode Teacher 格码致知1 分钟前
Pandas教学-18:number与numeric的区别
python·pandas
梦想不只是梦与想3 小时前
Python 中subprocess 模块:执行外部命令
python·subprocess·调用外部命令
懂点Tech3 小时前
ctfshow MISC入门图片篇(信息附加):misc41解题思路
开发语言·python
金銀銅鐵4 小时前
[Java] 用 GUI 展示 EnumSet 增减元素时的内部变化(上)
java·后端·ai编程
念何架构之路5 小时前
go-grpc设计思想
开发语言·后端·golang
system_error_x5 小时前
SpringBoot 集成 Thymeleaf 简洁入门
java·spring boot·后端
步行cgn7 小时前
Spring MVC 视图机制的核心接口与类
java·开发语言·后端·spring·mvc
码事漫谈8 小时前
AI 读你的提示词,其实很没耐心
后端
爱上纯净的蓝天8 小时前
不用云做 RAG:一个本地笔记问答工具的取舍与坑
python·开源·大模型·rag·本地部署
cspttty8 小时前
2027风险管理岗准备路线:数学与应用数学如何补齐金融、SQL与Python
开发语言·python·金融