在 Django 管理页面中注册应用程序中的每个表/类 [英] Register every table/class from an app in the Django admin page

查看:13
本文介绍了在 Django 管理页面中注册应用程序中的每个表/类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 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屋!

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