Feanor Feanor - 4 months ago 80
Python Question

Django get list of models in application

So, i have a file models.py in MyApp folder:

from django.db import models
class Model_One(models.Model):
...
class Model_Two(models.Model):
...
...


It can be about 10-15 classes.
How to find all models in the MyApp and get their names?

Since models are not iterable, i don't know if this is even possible.

Answer

This is the best way to accomplish what you want to do:

from django.db.models import get_app, get_models

app = get_app('my_application_name')
for model in get_models(app):
    # do something with the model

In this example, model is the actual model, so you can do plenty of things with it:

for model in get_models(app):
    new_object = model() # Create an instance of that model
    model.objects.filter(...) # Query the objects of that model
    model._meta.db_table # Get the name of the model in the database
    model._meta.verbose_name # Get a verbose name of the model
    # ...

UPDATE

for newer versions of Django check Sjoerd answer below

Comments