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
  • 298,606
  • 55
  • 578
  • 516
Ankita Nand
  • 137
  • 1
  • 12

2 Answers2

3

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
  • 298,606
  • 55
  • 578
  • 516
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
  • 9,457
  • 5
  • 39
  • 35