Get class name of django model

Viewed 96166

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?

6 Answers

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

You could also retrieve the model name from the model's Meta class. This works on the model class itself as well as any instance of it:

# Model definition
class Book(models.Model):
    # fields...

    class Meta:
        verbose_name = 'book'
        verbose_name_plural = 'books'


# Get some model
book = Book.objects.first()

# Get the model name
book._meta.verbose_name

Setting verbose_name and verbose_name_plural is optional. Django will infer these values from the name of the model class (you may have noticed the use of those values in the admin site).

https://docs.djangoproject.com/en/3.0/ref/models/options/#verbose-name

Related