Django获取应用程序中的模型列表
问题描述:
所以,我在MyApp文件夹中有一个文件models.py:
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):
...
...
它可以是大约10-15个类。
如何查找MyApp中的所有模型并获取他们的名字?
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.
答
这是完成您想要做的最好的方法:
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
在这个例子中, code> 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检查 Sjoerd 回答以下
for newer versions of Django check Sjoerd answer below