Get class name of django model

I have a django model:

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

and I want to have the model name as string: 'Book'. When I try to get it this way:

Book.__class__.__name__

it returns 'ModelBase'.

Any idea?


Solution 1:

Try Book.__name__.

Django models are derived from the ModelBase, which is the Metaclass for all models.

Solution 2:

Instead of doing Book.__class__.__name__ on class itself, if you do it over a book object, then book_object.__class__.__name__ will give you 'Book' (i.e the name of the model)

Solution 3:

As suggested by the answer above, you can use str(Book._meta).

This question is quite old, but I found the following helpful (tested on Django 1.11, but might work on older...), as you may also have the same model name from multiple apps.

Assuming Book is in my_app:

print(Book._meta.object_name)
# Book

print(Book._meta.model_name)
# book

print(Book._meta.app_label)
# my_app

Solution 4:

I got class name by using,

str(Book._meta)

Book.__class__.__name__  -> this will give you the ModelBase