简体   繁体   中英

Django Model load choices from a json file

I am writing a Django User model which contains a mobile_country_code field. This field needs to be populated from a list of ISD codes, pre-populated in a json file. What is the best pythonic way to do the same?

My current implementation, which is working:

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

Other Possible options listed below. Which one is better to use?

  • Using a model's __init__ method to create COUNTRIES_ISD_CODES
  • Importing a library method, like:

     from library import import_countries_isd_codes class User(models.Model): mobile_country_code = models.CharField(choices=import_countries_isd_codes())

Try this, Since Django only takes tuples

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)

in the model pass something like


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

Works for when there's more than one value per key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM