Search code examples
djangodjango-modelsproxy-classes

How to use variable to choose which Proxy model will be used in Django


I have a model

#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

in my view

#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(...)

I don't really know how to do it... Obviously I can write foo = Table_Name.objects.get_or_create(...) in between request.POST calls, but it would bee too long and hard to debug in the future.

My ideas was also about creating a function in models.py to check that, but again don't know how to do that, or may be somehow check it in my html template.

Thank you


Solution

  • 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()