0

有没有办法做这样的事情: - 我有一门课:

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 中是否可以创建此模型的实例?对象=数据(名称=“约翰”)???

4

1 回答 1

1

您可以为此使用工厂模式。使用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)
于 2015-09-08T11:06:03.457 回答