python - 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")
下面列出了其他可能的选项。哪个更好用?
- 使用模型的
__init__
方法创建COUNTRIES_ISD_CODES
导入库方法,例如:
from library import import_countries_isd_codes class User(models.Model): mobile_country_code = models.CharField(choices=import_countries_isd_codes())
解决方案
试试这个,因为 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'])
适用于每个键有多个值的情况。
推荐阅读
- flutter - 如何在颤动中覆盖 VLC 播放器视频
- javascript - cookie 没有在 nextjs 中发送到服务器
- ruby-on-rails - Ruby 视图无法将值映射到布尔值
- spring-boot - 微服务中的事务发件箱模式与 ChainedKafkaTransactionManager
- controller - 在 Business Central 的启动 (standalone.bat) 中不断收到 KieServer-ControllerConnect 错误 401
- firebase - Flutter - 来自 Firebase 的英雄小部件子图像 url
- c++ - 正确使用 RDRAND(片上生成器)作为 std::random_device 与 Visual C++ 的随机库
- html - margin-top 和 marin-left 不知从何而来
- javascript - 不使用背景过滤器在视频顶部的整个屏幕上覆盖半透明
- angular - 如何在 Angular 订阅块中测试代码,而不会在后续订阅块中覆盖值?