Django获取应用程序中的模型列表 [英] Django get list of models in application

查看:98
本文介绍了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

这篇关于Django获取应用程序中的模型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆