从Django管理页面中的应用程序注册每个表/类 [英] Register every table/class from an app in the Django admin page
问题描述
我有一个名为 doors
的应用程序,而我的 models.py
的应用程序有10个表/类。在我的 admin.py
下,如何在文件 models.py
中注册每个模型?
I have an app named doors
and my models.py
for the app has 10 tables/class. Under my admin.py
, how do I register every model in the file models.py
?
例如,当前我必须对其进行硬编码:
For example, currently I have to hardcode it:
from django.contrib import admin
from doors.models import *
admin.site.register(Group)
admin.site.register(Item)
admin.site.register(ItemType)
admin.site.register(Location)
admin.site.register(Log)
admin.site.register(Order)
admin.site.register(Property)
admin.site.register(User)
admin.site.register(Vendor)
是否可以找到 models.py
中的每个类并循环注册每个类的方法?还是可以在Django中使用某种通配符?
Is there a way I perhaps find every class in models.py
and loop through and register each class? Or is there some kind of wildcard I can use with Django?
推荐答案
我通过@arie的链接(对于django< ; 1.8):
I figured it out with @arie's link (for django < 1.8):
from django.contrib import admin
from django.db.models import get_models, get_app
for model in get_models(get_app('doors')):
admin.site.register(model)
但是我想知道是否可以在没有 get_app
的情况下做到这一点……代码不够聪明,无法知道其名称。自己的应用?
But I wonder if I can do this without get_app
... Couldn't the code be smart enough to know the name of its own app?
这篇关于从Django管理页面中的应用程序注册每个表/类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!