0

我有一个模型

#models.py
class BaseModel(model.Models)
    some_field = ...

class Proxy_1(BaseModel)
    class Meta:
        proxy=True

class Proxy_2(BaseModel)
    class Meta:
        proxy=True

class Proxy_3(BaseModel)
    class Meta:
        proxy=True

在我看来

#views.py
    #check the field and based on the value
    #choose appropriate Proxy model
    if request.POST['some_field'] == '1'
        # Table_Name = Proxy_1   ??????? ---HERE ---
    if request.POST['some_field'] == '2'
        # Table_Name = Proxy_2   ??????? ---HERE ---
    if request.POST['some_field'] == '3'
        # Table_Name = Proxy_3   ??????? ---HERE ---

    foo = Table_Name.objects.get_or_create(...)

我真的不知道该怎么做...显然我可以在 request.POST 调用之间编写 foo = Table_Name.objects.get_or_create(...) ,但是将来会太长且难以调试。

我的想法也是关于在 models.py 中创建一个函数来检查它,但又不知道该怎么做,或者可能以某种方式在我的 html 模板中检查它。

谢谢

4

1 回答 1

1

一个简单的解决方案是为您的模型创建一个表单并覆盖 save 方法以返回正确的代理实例:

# forms.py
PROXIES = {'1': Proxy_1, '2': Proxy_2, '3': Proxy_3}
class BaseModelForm(forms.ModelForm):
    class Meta:
        model = BaseModel

    def save(self, commit=True):
        instance = super(BaseModelForm, self).save(commit=True)
        if instance.some_field in PROXIES.keys():
            if commit:
                return PROXIES[instance.some_field].objects.get(pk=instance.pk)
            return PROXIES[instance.some_field](**self.cleaned_data)
        return instance

# views.py
def myview(request):
    form = BaseModelForm(request.POST or None)
    if form.is_valid():
        instance = form.save()
于 2012-07-27T18:59:11.943 回答