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

点个赞呗~

相关推荐
一个天蝎座 白勺 程序猿1 小时前
Python爬虫(11)Python数据存储实战:深入解析NoSQL数据库的核心应用与实战
开发语言·python·nosql
南玖yy2 小时前
C++ 的未来战场:从技术深耕到职业破局
c语言·开发语言·c++·后端·c++未来
喜欢吃豆2 小时前
大模型api压力测试
服务器·数据库·人工智能·python·prompt·压力测试
正在走向自律2 小时前
AI数字人:人类身份与意识的终极思考(10/10)
人工智能·python·数字孪生·ai数字人·多模态交互
weixin_456588153 小时前
【Spring Boot 注解】@ConfigurationProperties
spring boot·后端
神奇侠20243 小时前
基于tabula对pdf中多个excel进行识别并转换成word中的优化(四)
python·pdf·word·tabula
serve the people3 小时前
centos上安装python的3.13版本
linux·python·centos
九班长3 小时前
JMeter WebSocket 压测详细步骤(支持 ws+proto 协议)
开发语言·python·网络协议·jmeter·golang
Json_181790144803 小时前
闲鱼商品详情API接口概述及JSON数据参考
android·大数据·python
Silence4Allen4 小时前
Pycharm 代理配置
ide·python·pycharm·proxy·代理