Become a sponsor

本章概要
数据字典的完整使用流程,从新增字典类型到在代码中使用字典数据的实操指南。
数据字典是项目的基础配置功能,用于管理枚举类型的下拉选项。本章从「如何新增字典」到「如何在代码中使用」的完整实操流程。
数据字典由两层组成:
字典类型(dict) 字典项(dict_item)
+-- sys_user_status +-- 1 -> 正常
+-- sys_user_gender +-- 2 -> 停用
+-- article_type +-- 3 -> 删除
+-- ...| 层级 | 表 | 说明 |
|---|---|---|
| 字典类型 | django_dict | 字典分类(如「用户状态」「文章类型」) |
| 字典项 | django_dict_item | 字典的具体选项(如「1-正常」「2-停用」) |
需要为「培训方式」模块添加一个下拉选项:1-线上 2-线下 3-混合。
登录管理后台,进入「系统管理 -> 数据字典」:
| 字段 | 值 |
|---|---|
| 字典名称 | 培训方式 |
| 字典编码 | training_method |
| 状态 | 正常 |
在字典类型列表中点击「培训方式」,进入字典项管理:
| 字典值 | 字典标签 | 排序 |
|---|---|---|
| 1 | 线上 | 1 |
| 2 | 线下 | 2 |
| 3 | 混合 | 3 |
from application.dict_item import services as dict_item_services
# 获取字典项列表
items = dict_item_services.get_by_dict_code('training_method')
# 返回: [{"label": "线上", "value": "1"}, {"label": "线下", "value": "2"}, {"label": "混合", "value": "3"}]# 在分页查询中为记录补充字典名称
def _enrich_records(records):
status_map = dict_item_services.get_dict_map('sys_status')
for record in records:
record['statusName'] = status_map.get(str(record.get('status')), '未知')
return records<template>
<el-select v-model="form.trainingMethod" placeholder="请选择培训方式">
<el-option
v-for="item in dictOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useDictStore } from '@/store/dict';
const dictStore = useDictStore();
const dictOptions = ref([]);
onMounted(async () => {
dictOptions.value = await dictStore.loadDict('training_method');
});
</script>在 columns.ts 中使用 render 函数:
import { h } from 'vue';
import { ElTag } from 'element-plus';
export const columns = [
{
label: '培训方式',
prop: 'trainingMethod',
render(record) {
const map = { 1: '线上', 2: '线下', 3: '混合' };
const typeMap = { 1: 'success', 2: 'warning', 3: 'info' };
return h(ElTag, { type: typeMap[record.row.trainingMethod] }, {
default: () => map[record.row.trainingMethod] || '-'
});
},
},
];代码生成器会自动识别字段注释中的枚举格式(1-线上 2-线下 3-混合),并:
choices 列表dict_code(格式:{table_name}_{field_name})生成后需在后台手动创建对应的字典类型和字典项。
模块_字段 格式,如 user_status、article_type1-正常 2-停用 全项目保持一致dict_code 需在后台手动创建对应数据数据字典通过「字典类型 + 字典项」两层结构管理枚举选项。后端通过字典编码获取选项列表,前端通过 useDictStore 获取下拉数据。代码生成器会自动识别注释中的枚举格式并生成对应配置。