ChatGPT解决这个技术问题 Extra ChatGPT

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?


m
miku

Try Book.__name__.

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


v
vijay shanker

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)


This one helped me in my case. I merged 2 querysets that are of different models. In a loop I needed to get the class name of the object when I'm iterating.
Peter, how did you merge two querysets?? Or is the merged set just a list of model instances?? Thanks
O
OrangeDog

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

This should be the accepted answer for newer versions of Django.
You're correct @Bobort, it's working on Django version 2.2.3 too.
This is exactly what I needed. This works for both the model/class itself and an instance of the model.
M
Mohideen bin Mohammed

I got class name by using,

str(Book._meta)

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

Thanks; str(self.model._meta) is what I was looking for; as for the other give me the parent class.
If you want something more implicit than a call to string, then you can get the same (tried on Django 1.11) with: Book._meta.object_name or Book._meta.model_name. Then if you want the app name as well, that's accessible via Book._meta.app_label
H
Hussam
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'.


L
Leo

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