Import and register all classes from models in admin-django

回眸只為那壹抹淺笑 提交于 2019-12-24 20:11:21

问题


In myApp, I have multiple classes in models. I would like to import all of these classes in admin.py and register.

Is it possible without repetition such as

from django.contrib import admin
from .models import (classA,classB, classC)
  1. Could I import all the items without explicitly referring as done above
  2. Could I also register all at one time

Thanks

Jeff


回答1:


You can try this :-

import inspect
import models 

for name, obj in inspect.getmembers(models):
    if inspect.isclass(obj):
        admin.site.register(obj)

This will get all the class of models.py and register on admin under loop.

I have not try it but its work same for getting classes on python.




回答2:


you can register all model by using this:

from django.db.models.base import ModelBase from django.contrib import admin import models

for model_name in dir(models):
    model = getattr(models, model_name)
    if isinstance(model, ModelBase):
        admin.site.register(model)


来源:https://stackoverflow.com/questions/45232541/import-and-register-all-classes-from-models-in-admin-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!