class PO(models.Model)
qty = models.IntegerField(null=True)
cost = models.IntegerField(null=True)
total = qty * cost
Run Code Online (Sandbox Code Playgroud)
我将如何解决total = qty * cost上述问题.我知道它会导致错误,但不知道如何处理这个问题.
我需要创建一个枚举来表示 ISO 国家/地区代码。国家/地区代码数据来自 json 文件,可从以下位置获取:https ://github.com/lukes/ISO-3166-Countries-with-Regional-Codes
所以我所做的是:
data = json.load(open('slim-2.json'))
codes_list = [(data[i]['alpha-2'], int(data[i]['country-code']))
for i in range(len(data))]
CountryCode = enum.Enum('CountryCode', codes_list,)
names_dict = {int(data[i]['country-code']):data[i]['name']
for i in range(len(data))}
setattr(CountryCode, '_names', names_dict)
CountryCode.choices = classmethod(lambda cls:((member.value, name)
for name, member in cls.__members__.items()))
setattr(CountryCode, '__str__' ,lambda self: self.__class__._names[self.value])
Run Code Online (Sandbox Code Playgroud)
坦率地说,这段代码片段很丑陋。我研究了定义枚举类的替代方法,但无法拼凑出解决方案。有没有一种方法可以按以下形式定义枚举:
class CountryCode(enum.Enum):
data = json.load(open('slim-2.json'))
# Some code to define the enum members
@classmethod
def choices(cls):
# etc...
Run Code Online (Sandbox Code Playgroud)
关于如何执行此操作有什么建议吗?