Search code examples
djangodjango-rest-frameworkdjango-serializer

Access a serializer via a variable in drf


In the create method in my serializer I'm trying to send a portion of validated data to another serializer as below:

new_serializer = NewSerializer(validated_data.get('customer'))
new_serializer.save()

But in the place of NewSerializer I want to be able to use a variable. I have a dictionary where each model is mapped to its serializer.

my_dict = {"Model1": "Serializer1", "Model2": "Serializer2"}

The model name is available to me and I will use that to find out the corresponding serializer from the dictionary. I have over fifty serializers and I may have to use any one so importing all of them will not be feasible. I want to do something like this:

the_serializer = mydict.get('Model1')
new_serializer = the_serializer(validated_data.get('customer'))

Is there a way to achieve this?


Solution

  • I found a way to do this by using import_string in django. I had my app_name and model_name present which were used to import the serializer. All of my serializers are named in {model_name}Serializer format so this way worked for me.

    serializer_name = import_string(f"{app_name}.serializers {model_name}Serializer")
    ins = serializer_name(data = main_data)
    if ins.is_valid():
    ins.save()

    Here's the django documentation link.
    https://docs.djangoproject.com/en/4.0/ref/utils/?fbclid=IwAR22qaDgk0xT9nOY0lP4s3tVh2aKEleefFWQf_L6th5I0DQ56RUMpUmskpo#module-django.utils.module_loading