mardi 26 juillet 2022

How to auto load/ import model, serializer as per the conditional requirement in any view using Django

I am in need of an Auto Import for Custom Model and Serializer Accordingly as per the condition, in any view.

Problem Case: Here I created two Classes(VIEWS) in Django one is specifically taking requests and another is the Base class that will control all the requests using the (get_data()) function and returns the valid data and response.

SampleView.py:

from .src.views.BaseRequestClass import BaseRequestClass

class SampleView(APIView):
    def get(self, request):
        d = BaseRequestClass
        model = request.query_params.get('model') # Model name I am getting in Request
        data = d.get_data(model)
        return Response(data, status=status.HTTP_200_OK)

BaseClass.py:

class BaseRequestClass:
    def get_data(models):
        dictionary = {"stu": ['StudentModel', 'StudentSerializer']}
        if models =='stu':
            model = # here auto-import of the model required as per above dictionary only if condition matched else no import will take place for this model
            serializer = # here auto-import of the serializer required as per above dictionary only if condition matched else no import will take place for this model
        
        details = model.objects.all()
        serial = serializer(details, many=True).data
        return serial

Where is the mistake or issue while writing this and what code can help me to import in it that I don't have to import all together, just as per condition only those custom Models and Serializers get Import?

I hope this question will be understood if there is any doubt please let me know.





Aucun commentaire:

Enregistrer un commentaire