Get django model class name

I have a django model:

class Book(models.Model): [..] 

and I want the model name to be a string: "Book". When I try to do this:

 Book.__class__.__name__ 

it returns "ModelBase".

Any idea?

+66
django django-models
Aug 30 '10 at 10:25
source share
4 answers

Try Book.__name__ .

Django models are derived from ModelBase , which is a metaclass for all models.

+93
Aug 30 '10 at 10:29
source share

Instead of making Book.__class__.__name__ in the class itself, if you do this on a book object, then book_object.__class__.__name__ will provide you with a "Book" (that is, the name of the model)

+31
Oct 21 '13 at 6:41
source share

I got the class name using

 str(Book._meta) Book.__class__.__name__ -> this will give you the ModelBase 
+2
Jul 26 '17 at 7:59
source share
 class Book(models.Model): [..] def class_name(self): return self.__class__.__name__ 

Thus, whenever you call book.class_name (also in the template {{book.class_name}} ), it returns the name of the class, which is the "Book".

+1
Jan 30 '17 at 11:25
source share



All Articles