[Django]-Django DetailView dynamic model

3👍

You can override the get_queryset() method to return the appropriate model’s queryset after getting the model from model_kwarg.

To get the model from the model_type kwarg, you can create a MODEL_TYPE_KWARGS_TO_MODEL_MAPPING dictionary. It will return the model by performing lookup on it with model_type kwarg as key. Ofcourse, you will have to add error handling for invalid model_type cases.

You can do something like:

class DynamicModelUpdate(UpdateView):

    def get_queryset(self):
         model = MODEL_TYPE_KWARGS_TO_MODEL_MAPPING[self.kwargs['model_type']]
         return model.objects.all()

Leave a comment