Amistad
Amistad

Reputation: 7400

Find the model name from a Django Rest framework Serializer

I have a serializer from which I need to find the associated model name.This is how i did it:

In [30]: from my_app.serializers.PolicySerializer import PolicyCreateSerializer 

In [31]: model_name = PolicyCreateSerializer.Meta.model  

In[32]: model_name                                                                                                                                                                                                                                                      
Out[32]: my_app.models.Policy.Policy

What i need is the last part of that value separated by dots(Policy).However, the type of model_name is not a string and converting it to a string gives a weird string as follows:

In [33]: type(model_name)                                                                                                                                                                                                                                                
Out[33]: django.db.models.base.ModelBase

In [34]: str(model_name)                                                                                                                                                                                                                                                 
Out[34]: "<class 'my_app.models.Policy.Policy'>"

Is there an easier way to avoid this gnarly string and just get the Model name ?

Upvotes: 3

Views: 2883

Answers (1)

aman kumar
aman kumar

Reputation: 3156

Below will return string value

model_name = PolicyCreateSerializer.Meta.model.__name__

Upvotes: 10

Related Questions