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.

48118 次浏览

UPDATE

for newer versions of Django check Sjoerd answer below

Original answer from 2012: 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
# ...

From Django 1.7 on, you can use this code, for example in your admin.py to register all models:

from django.apps import apps
from django.contrib import admin
from django.contrib.admin.sites import AlreadyRegistered


app_models = apps.get_app_config('my_app').get_models()
for model in app_models:
try:
admin.site.register(model)
except AlreadyRegistered:
pass

An alternative is to use Content Types.

Each models for each application in INSTALLED_APPS get an entry in the ContentType models. This allow you, for exemple, to have a foreign key to a model.

>>> from django.contrib.contenttypes.models import ContentType
>>> ContentType.objects.filter(app_label="auth")
<QuerySet [<ContentType: group>, <ContentType: permission>, <ContentType: user>]>
>>> [ct.model_class() for ct in ContentType.objects.filter(app_label="auth")]
[<class 'django.contrib.auth.models.Group'>, <class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.auth.models.User'>]

Best answer I found to get all models from an app:

from django.apps import apps
apps.all_models['<app_name>']  #returns dict with all models you defined

Here's a quick-and-dirty, no-coding solution using dumpdata and jq:

python manage.py dumpdata oauth2_provider | jq -r '.[] | .model' | uniq

You could also clean up the jq command to get the format just to your liking.


Bonus: you can see counts of the different types of objects by adding the -c flag to uniq.

I came here because I want to automatically extract fixtures for every app.

This prints out commands to dump fixtures for all objects in your project. (I have moved my apps within an apps directory.)

from django.apps import apps
from django.conf import settings


print(
'\n'.join(
[
'\n'.join(
[
f'PYTHONPATH=.:apps django-admin dumpdata {app}.{model} --settings=my_project.settings > apps/{app}/fixtures/{model}.json'
for model in apps.all_models[app]
]
)
for app in settings.INSTALLED_APPS
]
)
)

Check you've activated your virtual environment so you're using the right django-admin. (Check with which django-admin.py.)

Only tangentially related to the original question, but might be useful for someone stumbling across this for the same reason I did. I'm on Django 2.2.4, haven't tested it elsewhere.

For my own use-case that had me stumble on this question, I was looking to see what app a model came from (for use with database router checks and whether to allow relationships, in case of different databases having the same model name).

For my case, it turns out that every model has a meta tag that indicates what app it came from. This may be helpful to others in the same situation.

For example, if a function is passed the model model, the app that defined that model is found in model._meta.app_label as a string. So for a database router, you could declare:

def allow_relation(self, obj1, obj2, **hints):
"""Determine whether to allow ForeignKey relationships between two objects"""
# if neither object is from MyApp, then this router doesn't care.
if 'MyApp' not in [obj1._meta.app_label, obj2._meta.app_label]:
return None  # None means "no opinion" so other routers can still chime in
else:
# at least one object is from MyApp, so allow foreignkey relationships.
return True

Taking off from @pedrotorres solution with some prudent inputs from @GiampaoloFerradini, this is what I am using finally:

from django.apps import apps


app_models = [model.__name__ for model in apps.get_models()] # Returns a "list" of all models created