204👍
Try Book.__name__
.
Django models are derived from the ModelBase
, which is the Metaclass for all models.
81👍
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
- [Django]-Django custom field validator vs. clean
- [Django]-How to access a dictionary element in a Django template?
- [Django]-Should I be adding the Django migration files in the .gitignore file?
72👍
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)
- [Django]-Find object in list that has attribute equal to some value (that meets any condition)
- [Django]-Validators = [MinValueValidator] does not work in Django
- [Django]-Creating a dynamic choice field
8👍
class Book(models.Model):
[..]
def class_name(self):
return self.__class__.__name__
With this way, whenever you called book.class_name()
in python code (also in the template {{book.class_name}}
) it will return class name which is ‘Book’.
- [Django]-Why won't Django use IPython?
- [Django]-Logging in Django and gunicorn
- [Django]-Django – limiting query results
8👍
I got class name by using,
str(Book._meta)
Book.__class__.__name__ -> this will give you the ModelBase
- [Django]-How can I check the size of a collection within a Django template?
- [Django]-Django admin and MongoDB, possible at all?
- [Django]-How do I filter ForeignKey choices in a Django ModelForm?
6👍
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
- [Django]-Is this the right way to do dependency injection in Django?
- [Django]-How do I make many-to-many field optional in Django?
- [Django]-Django rest framework: query parameters in detail_route