Site icon LD Talent Blog

How to import a serializer from a variable in DRF?

Hire the author: Bijita K

There can arise use cases in which we may need to import the serializer using a variable. In order to do this first, we would need to know the app’s name in which the serializer is stored. One of the ways we can do this is by creating a dictionary that maps serializers to the apps they are stored in.

Let’s suppose we have a serializer named “my_serializer” stored in the app named “myapp” from where it needs to be imported. Then our dictionary will be as follows:

The key of the dictionary needs to be unique. Therefore, I suggest using the name of the serializer as the key and the name of the app used to import it as the value. An app can have many serializers but a serializer belongs to only one app.

After this, we are going to utilize the import_string function of Django. It is used to import a dotted module path. Then it returns the attribute or class designated by the last name in the path.

If the serializer’s name is stored in the variable ‘serializers_name’ then we will first extract the app’s name.

We are attempting to import a serializer from inside the serializers.py file that resides in the Django app. Now we can use the app’s name and serializer’s name to import the serializer as shown in the code.

We can use the above-imported serializer to send the data and create a new instance as shown below:

To know more about import_string we can refer to the Django documentation.

https://docs.djangoproject.com/en/4.0/ref/utils/?fbclid=IwAR22qaDgk0xT9nOY0lP4s3tVh2aKEleefFWQf_L6th5I0DQ56RUMpUmskpo#module-django.utils.module_loading

Now that the API is working you can refer to this article to learn to host your application.

Hire the author: Bijita K

Exit mobile version