[Answer]-How to use variable to choose which Proxy model will be used in Django

1๐Ÿ‘

โœ…

A simple solution is creating a form for your model and override the save method to return the proper proxy instance:

# 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()
๐Ÿ‘คGonzalo

Leave a comment