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

点个赞呗~

相关推荐
容若只如初见2 小时前
项目实战--Spring Boot + Minio文件切片上传下载
java·spring boot·后端
码农爱java2 小时前
Spring Boot 中的监视器是什么?有什么作用?
java·spring boot·后端·面试·monitor·监视器
Apifox.3 小时前
什么是 HTTP POST 请求?初学者指南与示范
后端·http·学习方法·web
2401_858120263 小时前
探索sklearn文本向量化:从词袋到深度学习的转变
开发语言·python·机器学习
无名指的等待7123 小时前
SpringBoot实现图片添加水印(完整)
java·spring boot·后端
bigbearxyz5 小时前
Java实现图片的垂直方向拼接
java·windows·python
立秋67895 小时前
使用Python绘制堆积柱形图
开发语言·python
jOkerSdl5 小时前
第三十章 方法大全(Python)
python
小白学大数据5 小时前
HTML内容爬取:使用Objective-C进行网页数据提取
大数据·爬虫·python·html·objective-c·cocoa
逆境清醒6 小时前
开源数据科学平台Anaconda简介
人工智能·python·深度学习·机器学习·anaconda