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.
Now that the API is working you can refer to this article to learn to host your application.
Hello Bijita, nice read. I had a question are there any benefits to using this kind of an import as opposed to just importing the serializer directly?
Thank you Mainak! And yes there are. There can be situations when you may need to use a serializer which will have to be chosen according to the input. In such cases, if you have many serializers it will not be feasible to import all the serializers directly. This situation is when the above technique has the most benefits and sometimes may be the only feasible way.