有没有办法做这样的事:-我有一门课:
class HumanModel():
def __init__(self, name=None):
self.name = name
...
class OtherHumanModel():
def __init__(self, name=None):
self.name = name
...等。
我有一张表格
class SelectForm(forms.Form):
selection = forms.ChoiceField(
choices=[
(HumanModel, 'Human'),
(OtherHumanModel, 'Other Human')
]
)我认为:
def MyView(request):
if request.method == "GET":
form = SelectForm()
return render(request, 'some-html', {
"form": form
})
if request.method == "POST":
data = request.POST['selection']
#make a instance?
return render(...)例如,在数据中是HumanModel,但是在unicode中有可能生成这个模型的实例吗?object =data(name=“John”)?
发布于 2015-09-08 11:06:03
你可以用工厂模式来处理这个问题。使用HumanModel.__name__引用所选内容中的类名,而不是使用工厂中的名称来创建类的具体实例。
class SelectForm(forms.Form):
selection = forms.ChoiceField(
choices=[
(HumanModel.__name__, 'Human'),
(OtherHumanModel.__name__, 'Other Human')
]
)
class HumanModelFactory(object):
def __init__(self, model_name):
if model_name == "HumanModel":
return HumanModel()
if model_name == "OtherHumanModel":
return OtherHumanModel()
# usage
model_name = request.POST['selection'] # e.g. 'HumanModel'
instance = HumanModelFactory(model_name)https://stackoverflow.com/questions/32454895
复制相似问题