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.
Asked
Active
Viewed 1.2k times
12

Super Kai - Kazuya Ito
- 22,221
- 10
- 124
- 129

Ken1995
- 189
- 1
- 2
- 11
-
7Possible duplicate of [Getting the class name of an instance in Python](https://stackoverflow.com/questions/510972/getting-the-class-name-of-an-instance-in-python) – internet_user Mar 14 '18 at 00:55
4 Answers
27
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

Ykh
- 7,567
- 1
- 22
- 31
1
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

G. Vallereau
- 141
- 3
- 8
0
With __name__
, you can get a model name in str
type as shown below:
from .models import MyModel
print(MyModel.__name__) # MyModel

Super Kai - Kazuya Ito
- 22,221
- 10
- 124
- 129
-3
By defining the str or unicode method ?

AstroMax
- 112
- 9
-
1defining str gives a string name for the "model_instance" not the model – Ken1995 Mar 14 '18 at 00:56