我有一个模特
#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模板中检查它。
谢谢
答案 0 :(得分: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()