說我的問題數(shù)量未知.例如:
>天藍(lán)色[是/否]
>你[約會(huì)]出生的日期
>什么是pi [3.14]
>什么是大型整合[100]
現(xiàn)在,這些問題中的每一個(gè)都提出了一個(gè)不同但非常類型的答案(布爾值,日期,浮點(diǎn)數(shù),整數(shù)).本土django可以在模型中愉快地處理這些問題.
class SkyModel(models.Model): question = models.CharField("Is the sky blue") answer = models.BooleanField(default=False)class BirthModel(models.Model): question = models.CharField("What date were your born on") answer = models.DateTimeField(default=today)class PiModel(models.Model) question = models.CharField("What is pi") answer = models.FloatField()
但這有一個(gè)明顯的問題,即每個(gè)問題都有一個(gè)特定的模型 – 所以如果我們以后需要添加一個(gè)問題,我必須更改數(shù)據(jù)庫.呸.所以現(xiàn)在我想得到想象 – 如何通過答案類型轉(zhuǎn)換自動(dòng)地設(shè)置模型?
ANSWER_TYPES = ( ('boolean', 'boolean'), ('date', 'date'), ('float', 'float'), ('int', 'int'), ('char', 'char'),)class Questions(models.model): question = models.CharField(() answer = models.CharField() answer_type = models.CharField(choices = ANSWER_TYPES) default = models.CharField()
所以在理論上這將做到以下幾點(diǎn):
>當(dāng)我建立自己的觀點(diǎn)時(shí),我會(huì)看到答案的類型,并確保我
只有這個(gè)價(jià)值.
>但是當(dāng)我想將該答案拉回來時(shí),它將以answer_type指定的格式返回?cái)?shù)據(jù).例3.14作為浮點(diǎn)而不是作為str返回.
我該如何進(jìn)行這種自動(dòng)轉(zhuǎn)換?或者有人可以提出更好的方法嗎?
非常感謝??!
解決方法:
我實(shí)際上只是遇到了有關(guān)可擴(kuò)展用戶設(shè)置的這類問題.我的解決方案是將模型中的類型存儲(chǔ)在CharField中,并使用getter通過智能使用__builtin__和getattr進(jìn)行類型轉(zhuǎn)換.這是我的代碼(適應(yīng)您的需求):
VALUE_TYPE_CHOICES = ( ("unicode", "Unicode String"), ("int", "Integer"), ("bool", "Boolean"),)class Setting(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) type = models.CharField(max_length=50, choices=VALUE_TYPE_CHOICES) default_value = models.CharField(max_length=127)def get_setting(user, setting_id): profile_setting = #get the user's specific setting value here, not relevant type = getattr(__builtin__, profile_setting.setting.type) if type is bool: return type(int(profile_setting.value)) else: return type(profile_setting.value)
那里有一個(gè)問題:bool(‘0’)實(shí)際上返回True,所以我選擇在類型轉(zhuǎn)換為bool之前進(jìn)行類型轉(zhuǎn)換為int.還有其他方法可以實(shí)現(xiàn)這一點(diǎn),例如使用ast模塊的literal_eval方法.總的來說,這種模式是有效的.
來源:https://www.icode9.com/content-1-349701.html聯(lián)系客服