Django get list of models in application

2019-01-10 22:20发布

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.

5条回答
狗以群分
2楼-- · 2019-01-10 22:42

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.

查看更多
女痞
3楼-- · 2019-01-10 22:44

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'>]
查看更多
做自己的国王
4楼-- · 2019-01-10 22:45

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
查看更多
乱世女痞
5楼-- · 2019-01-10 22:52

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
    # ...
查看更多
家丑人穷心不美
6楼-- · 2019-01-10 22:53

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
查看更多
登录 后发表回答