'Get model name from instance
How can I get a model name as a "string" from a model instance.
I know you can do something like type(model_instance)
but this is returning the class itself as an object <Model_Name: >
not as a string.
Solution 1:[1]
from user.models import User
user = User.objects.create_user(tel='1234567890', password='YKH0000000')
print(user._meta.model)
<class 'user.models.User'>
print(user._meta.model.__name__)
User
print(user.__class__.__name__)
User
Solution 2:[2]
To stay close to the question, type(instance).__name__
is a valide answer (which is the one given in this older question)
So using @Ykh example:
from user.models import User
user = User.objects.create_user(tel='1234567890', password='YKH0000000')
print(type(user).__name__)
User
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ykh |
Solution 2 | G. Vallereau |