113👍
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
94👍
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
# ...
- [Django]-Django REST Framework custom fields validation
- [Django]-CSRF Failed: CSRF token missing or incorrect
- [Django]-Nginx doesn't serve static
38👍
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
- [Django]-How to import csv data into django models
- [Django]-How to add url parameters to Django template url tag?
- [Django]-Django model manager objects.create where is the documentation?
9👍
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
- [Django]-Add inline model to django admin site
- [Django]-How does Django's nested Meta class work?
- [Django]-Sort order of Django Admin records
3👍
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'>]
- [Django]-What's the best way to store a phone number in Django models?
- [Django]-What is a "slug" in Django?
- [Django]-Simple guestbook django: __init__() takes 1 positional argument but 2 were given
2👍
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
.
- [Django]-How to force application version on AWS Elastic Beanstalk
- [Django]-Bypass confirmation prompt for pip uninstall
- [Django]-Getting Django admin url for an object
1👍
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.
- [Django]-Django aggregate or annotate
- [Django]-Django Model Field Default Based Off Another Field in Same Model
- [Django]-Django Model MultipleChoice
1👍
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
- [Django]-Problems with contenttypes when loading a fixture in Django
- [Django]-Django 2 – How to register a user using email confirmation and CBVs?
- [Django]-You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application