首页 > 解决方案 > Django 模型从 json 文件加载选择

问题描述

我正在编写一个User包含mobile_country_code字段的 Django 模型。此字段需要从 ISD 代码列表中填充,预先填充在 json 文件中。做同样事情的最好的pythonic方法是什么?

我当前的实现,正在运行:

json_data/countries.json

[
    ...
    {
        "name": "Malaysia",
        "dial_code": "+60",
        "code": "MY"
    },
    ...
]

project/app/models.py

import json, os

class User(models.Model):
    with open(os.path.dirname(__file__)+'/json_data/countries.json') as f:
        countries_json = json.load(f)
        COUNTRIES_ISD_CODES = [(str(country["dial_code"]), str(country["name"])) for country in countries_json]

    mobile_country_code = models.CharField(choices=COUNTRIES_ISD_CODES, help_text="Country ISD code loaded from JSON file")

下面列出了其他可能的选项。哪个更好用?

标签: pythondjangodjango-models

解决方案


试试这个,因为 Django 只接受元组

def jsonDjangoTupple(jsonData):
    """
    Django only takes tuples (actual value, human readable name) so we need to repack the json in a dictionay of tuples
    """
    dicOfTupple = dict()
    for key, valueList in jsonData.items():
        dicOfTupple[str(key)]=[(value,value) for value in valueList]
    return dicOfTupple
json_data = jsonDjangoTupple(jsonData)

在模型中传递类似


class User(models.Model):
    code = models.CharField(max_length=120,choices=json_data['code'])

适用于每个键有多个值的情况。


推荐阅读