1

I am trying to get the names of the classes I defined in my models.py file. The closest I could get is to recover all the models in the application:

modelsList = django.apps.apps.get_models (include_auto_created=False)` 

which gives:

<class 'django.contrib.admin.models.LogEntry'>
<class 'django.contrib.auth.models.Permission'>
<class 'django.contrib.auth.models.Group'>
<class 'django.contrib.auth.models.User'>
<class 'django.contrib.contenttypes.models.ContentType'>
<class 'django.contrib.sessions.models.Session'>
<class 'app.models.Project'>
<class 'app.models.User'>
<class 'app.models.File'>

But I wanted only the string 'Project', 'User', 'File'. Is there anyway I can get that?

Alasdair
  • 278,338
  • 51
  • 534
  • 489
Ankita Nand
  • 117
  • 10

2 Answers2

2

You can get the model name for a model Model with Model._meta.object_name. So you could do something like:

import django.apps
models = django.apps.apps.get_models(include_auto_created=False)
model_names = [m._meta.object_name for m in models]
Alasdair
  • 278,338
  • 51
  • 534
  • 489
1

Based on a answer from here:

from django.apps import apps

def get_models(app_name):
    myapp = apps.get_app_config(app_name)
    return myapp.models.values()
Community
  • 1
  • 1
Tiago
  • 8,929
  • 5
  • 38
  • 35