How to get a model name from the instance as a string in Django?
Asked Answered
B

4

13

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.

Burning answered 14/3, 2018 at 0:54 Comment(1)
Possible duplicate of Getting the class name of an instance in PythonNoguchi
C
29
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
Catamount answered 14/3, 2018 at 1:7 Comment(0)
S
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
Spaceband answered 11/4, 2022 at 16:27 Comment(0)
A
0

With __name__, you can get a model name in str type as shown below:

from .models import MyModel
              
print(MyModel.__name__) # MyModel
Arginine answered 11/5, 2023 at 22:28 Comment(0)
E
-3

By defining the str or unicode method ?

Emelineemelita answered 14/3, 2018 at 0:55 Comment(1)
defining str gives a string name for the "model_instance" not the modelBurning

© 2022 - 2024 — McMap. All rights reserved.